IsEnabled button in datagrid mvvm wpf - c#

How to enable/disable button inside datagrid using mvvm, where column status equals some value in c#?
Thanks.
P.S. I'm new in mvvm and wpf.
Edited:
My code only prints data in Datagrid. I want to disable edit button when column status equals to 1.
You can see my code below.
Model file
public class Reestr
{
private int id;
private string date;
private string market;
private int status;
public int Id
{
get { return id; }
set {
id = value;
}
}
public string Date
{
get { return date; }
set {
date = value;
}
}
public string Market
{
get { return market; }
set {
market = value;
}
}
public int Status
{
get { return status; }
set {
status = value;
}
}
}
ViewModel file
public ReestrViewModel()
{
reestr = GetListOfReestrs();
reestr.Add(new Reestr() { Date = "01.08.2017", Market = "Market1", Status = 0 });
reestr.Add(new Reestr() { Date = "02.08.2017", Market = "Market2", Status = 1 });
}
public ObservableCollection<Reestr> ReestrItems
{
get { return reestr; }
}
public ObservableCollection<Reestr> GetListOfReestrs()
{
return reestr;
}
Xaml file:
<DataGrid GridLinesVisibility="All"
AutoGenerateColumns="False"
CanUserAddRows="False"
x:Name="ReestrDataGrid"
ItemsSource="{Binding ReestrViewModel.ReestrItems}">
<DataGrid.Columns>
<DataGridTextColumn Header="ID"
Binding="{Binding Id}"
IsReadOnly="True"
Visibility="Hidden"
Width="*"/>
<DataGridTextColumn Header="Date"
Binding="{Binding Date}"
IsReadOnly="True"
Width="*"/>
<DataGridTextColumn Header="Market"
Binding="{Binding Market}"
IsReadOnly="True"
Width="*"/>
<DataGridTextColumn Header="Status"
Binding="{Binding Status}"
IsReadOnly="True"
Width="*"/>
<DataGridTemplateColumn Header="Operations" Width="200">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button x:Name="ViewButton"
Click="ViewButton_Click"></Button>
<Button x:Name="EditButton"></Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

You could use a Style with a DataTrigger:
<Button x:Name="EditButton">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="1">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>

Related

new row in datagrid with custom data

I have two datagrids. The first one is an overview about a time tracking. The second one shows some details.
For example:
The first datagrid contains each day, where a employee works. The second datagrid contains the time stamping for a day.
However, when I add a new stamping row, the controls in the datagrid are empty. That is not really a problem but the datepicker shows the date 01/01/0001.
what i want is when i add a new row, the date field should be filled with the date from the first datagrid.
VIEW:
<DataGrid Grid.Column="0"
IsReadOnly="True"
AutoGenerateColumns="False"
Grid.Row="0"
x:Name="DgStundenView"
Margin="0 0 10 0"
SelectedItem="{Binding SelectedItem}"
ItemsSource="{Binding TimeOverviewList}">
<DataGrid.Columns>
<DataGridTextColumn Header="Wochentag" Binding="{Binding Wochentag}" />
<DataGridTextColumn Header="Datum" Binding="{Binding Tag}" />
<DataGridTextColumn Header="Arbeitszeit Soll" Binding="{Binding ArbeitszeitInStunden}" />
<DataGridTextColumn Header="Arbeitszeit gesamt" Binding="{Binding GesamtDauerInStunden}" />
<DataGridTextColumn Header="Pausenzeit" Binding="{Binding Pausenzeit}" />
<DataGridTextColumn Header="Pausendifferenz" Binding="{Binding PausenDifferenzInStunden}" />
<DataGridTextColumn Header="Arbeitszeit inkl. Pause" Binding="{Binding TatsaechlicheDauerInStunden}" />
<DataGridCheckBoxColumn Header="Status" Binding="{Binding StempelungVorhanden,Mode=OneWay}" />
<DataGridTextColumn Header="Info" Binding="{Binding Info}" />
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Wochentag}" Value="Sa">
<Setter Property="Background" Value="LightGray" />
</DataTrigger>
<DataTrigger Binding="{Binding Wochentag}" Value="So">
<Setter Property="Background" Value="LightGray" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
<DataGrid Grid.Column="0"
Grid.Row="1"
x:Name="DgStempelungen"
Margin="0 10 10 0"
AutoGenerateColumns="False"
CanUserAddRows="True"
SelectedItem="{Binding SelectedValue}"
ItemsSource="{Binding TimeDetailList}">
<DataGrid.Resources>
<x:Array x:Key="Reasons" Type="system:String">
<system:String>NICHT ANWENDBAR</system:String>
<system:String>KRANK</system:String>
<system:String>GANZER TAG URLAUB</system:String>
</x:Array>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" IsReadOnly="True" Binding="{Binding Id}"/>
<DataGridTemplateColumn Header="KOMMEN DATUM">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding ComeBooking}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="KOMMEN UHRZEIT">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<materialDesign:TimePicker Text="{Binding ComeBookingTime, StringFormat=t}"
Is24Hours="True">
</materialDesign:TimePicker>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="GEHEN DATUM">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DatePicker SelectedDate="{Binding GoBooking}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="GEHEN UHRZEIT">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<materialDesign:TimePicker Text="{Binding GoBookingTime, StringFormat=t}"
Is24Hours="True">
</materialDesign:TimePicker>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridComboBoxColumn Header="GRUND"
ItemsSource="{StaticResource Reasons}"
TextBinding="{Binding Info}"/>
</DataGrid.Columns>
</DataGrid>
VIEW MODEL
[CanBeNull] private ClassTimeTrackingDayStamp _selectedItem;
[CanBeNull]
public ClassTimeTrackingDayStamp SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged();
if (_selectedItem != null)
TimeDetailList = new ObservableCollection<ClassTimeTrackingTimeStamp>(_selectedItem.Stempelungen);
}
}
private ObservableCollection<ClassTimeTrackingDayStamp> _timeOverviewList;
public ObservableCollection<ClassTimeTrackingDayStamp> TimeOverviewList
{
get { return _timeOverviewList; }
set
{
_timeOverviewList = value;
OnPropertyChanged();
}
}
[CanBeNull] private ObservableCollection<ClassTimeTrackingTimeStamp> _timeDetailList;
[CanBeNull]
public ObservableCollection<ClassTimeTrackingTimeStamp> TimeDetailList
{
get { return _timeDetailList; }
set
{
_timeDetailList = value;
OnPropertyChanged();
}
}
MODEL
public class ClassTimeTrackingTimeStamp : ViewModelBase
{
public DateTime ComeBooking { get; set; }
public DateTime GoBooking { get; set; }
public TimeSpan ComeBookingTime { get; set; }
public TimeSpan GoBookingTime { get; set; }
public int Id { get; set; }
public string Info { get; set; }
}
Update
EVENT OVER MVVM VIEW
<DataGrid Grid.Column="0"
Grid.Row="1"
x:Name="DgStempelungen"
Margin="0 10 10 0"
AutoGenerateColumns="False"
CanUserAddRows="True"
SelectedItem="{Binding SelectedValue}"
ItemsSource="{Binding TimeDetailList}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="AddingNewItem">
<i:InvokeCommandAction Command="{Binding Path=AddNewItemCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
...
VIEW MODEL
public ICommand AddNewItemCommand { get; set; }
#endregion Properties
#region Events
public event EventHandler AddNewItemEventHandler;
#endregion
#region Constructor
public WTimeClockOverviewVM()
{
AddNewItemCommand = new RelayCommand(o =>
{
this.AddNewItemEventHandler?.Invoke(this, EventArgs.Empty);
});
}
CODE BEHIND
public WTimeClockOverview()
{
InitializeComponent();
var vm = (WTimeClockOverviewVM)DataContext;
if(vm == null) return;
vm.AddNewItemEventHandler += (sender, args) =>
{
var selectedItemInFirstDg = vm.SelectedItem;
if (selectedItemInFirstDg != null)
{
var newItem = new ClassTimeTrackingTimeStamp();
newItem.ComeBooking = selectedItemInFirstDg.Tag;
}
};
}
Thank you for your help :)
Best regards
Levin
In second DataGrid, you can subscribe to AddingNewItem event
<DataGrid x:Name="DgStempelungen"
AddingNewItem="DgStempelungen_OnAddingNewItem"
...
In code behind
private void DgStempelungen_OnAddingNewItem(object sender, AddingNewItemEventArgs e)
{
// I'll assume that the Model's Name in first DataGrid collection is StudentItem!
var selectedItemInFirstDg = DgStundenView.SelectedItem as StudentItem;
// or you can get the selected item from the DataContext:
// (DgStundenView.DataContext as MyViewModel)?.SelectedItem;
if (selectedItemInFirstDg != null){
// create the new row with data from selectedItemInFirstDg, ex. date, etc...
e.NewItem = new ClassTimeTrackingDayStamp
{
ComeBooking = selectedItemInFirstDg.Date; // for example
};
}
}

How to set selected items in MVVM using SelectionMode="Extended"?

Goal
I currently have an app that select the items only by selecting the check box. Like so:
My goal is to multi select items (Which highlights the selected rows), right click and have a data context menu item to select, selected items.
Desired Output
As an example, this would be my desired output (Obviously not selecting the checkboxes manually).
Question
What would a good starting point to achieve this output? I couldn't find any examples.
Code
The Model is pretty simple.
public class OrdersModel : BaseVM
{
public int OrderId { get; set; } // Hidden
public string OrderNumber { get; set; }
public DateTime OrderDate { get; set; }
private bool _selectedRecord;
public bool SelectedRecord
{
get { return _selectedRecord; }
set
{
_selectedRecord = value;
OnPropertyChanged();
}
}
}
And this is my current XAML.
<DataGrid ItemsSource="{Binding Orders}"
AutoGenerateColumns="False"
SelectionMode="Extended"
CanUserAddRows="False">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=SelectedRecord}" Value="True">
<Setter Property="Background" Value="LightGray" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<!--Columns Used-->
<DataGrid.Columns>
<!--Select All Column-->
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<CheckBox Content="Select All"
IsChecked="{Binding DataContext.SelectAll, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"
Command="{Binding DataContext.ToggleAllOrdersCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=SelectedRecord, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Order Date"
Binding="{Binding OrderDate, StringFormat='{}{0:MM-dd-yyyy}'}" Width="*"
IsReadOnly="True"
FontSize="14" />
<DataGridTextColumn Header="Order Number"
Binding="{Binding OrderNumber}" Width="*"
IsReadOnly="True"
FontSize="14" />
</DataGrid.Columns>
<!--Menu Options-->
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Select Highlighted Rows" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
This solution worked for me. I took the liberty of changing some of your property names to avoid confusion as to what is "selected" and what is "checked".
OrdersModel:
public class OrdersModel : BaseVM
{
public int OrderId { get; set; } // Hidden
public string OrderNumber { get; set; }
public DateTime OrderDate { get; set; }
private bool _selected;
private bool _checked;
public bool Selected
{
get { return _selected; }
set { _selected = value; OnPropertyChanged(); }
}
public bool Checked
{
get { return _checked; }
set { _checked = value; OnPropertyChanged(); }
}
}
MainWindow.xaml.cs
<DataGrid ItemsSource="{Binding Orders}"
AutoGenerateColumns="False"
SelectionMode="Extended"
CanUserAddRows="False"
Tag="{Binding ElementName=myWindow,Path=DataContext}"
>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsSelected" Value="{Binding Selected}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Selected}" Value="True">
<Setter Property="Background" Value="LightGray" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<!--Columns Used-->
<DataGrid.Columns>
<!--Select All Column-->
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<CheckBox Content="Select All"
IsChecked="{Binding DataContext.SelectAll, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"
Command="{Binding DataContext.ToggleAllOrdersCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}}"/>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Checked, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Order Date"
Binding="{Binding OrderDate, StringFormat='{}{0:MM-dd-yyyy}'}" Width="*"
IsReadOnly="True"
FontSize="14" />
<DataGridTextColumn Header="Order Number"
Binding="{Binding OrderNumber}" Width="*"
IsReadOnly="True"
FontSize="14" />
</DataGrid.Columns>
<!--Menu Options-->
<DataGrid.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Select Highlighted Rows" Command="{Binding CheckSelectedCommand}"/>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
MainWindow.xaml.cs:
public class MainWindowViewModel : BaseVM
{
private ObservableCollection<OrdersModel> _orders;
private RelayCommand _checkSelectedCommand;
public MainWindowViewModel()
{
Initialize();
}
public ObservableCollection<OrdersModel> Orders
{
get
{
if (_orders == null)
_orders = new ObservableCollection<OrdersModel>();
return _orders;
}
}
public RelayCommand CheckSelectedCommand
{
get
{
if (_checkSelectedCommand == null)
_checkSelectedCommand = new RelayCommand(o => DoCheckSelectedRows());
return _checkSelectedCommand;
}
}
public void Initialize()
{
var dateTime = DateTime.Now.AddDays(-5);
for (int i = 0; i < 10; i++)
{
this.Orders.Add(new OrdersModel() { OrderId = i, OrderDate = dateTime.AddHours(4), OrderNumber = $"CA{i + 1593:0000}" });
}
}
private void DoCheckSelectedRows()
{
var selectedOrders = this.Orders.Where(o => o.Selected);
foreach (var order in selectedOrders)
{
order.Checked = true;
}
}
}
Solution will look like this:

How to Bind Different Lists to DataGridComboBoxColumn in each row using MVVM

I want to bind 'Units' property of ResultModel Class to DataGridComboBoxColumn. Other Bindings work fine but it cannot resolve 'Units' property. It recommends me 'Results' List instead of 'Units'. I want to use different Lists in each row.
You can see my View, ViewModel and Model Classes below.
View.xaml
<DataGrid x:Name="DataGrid" AutoGenerateColumns="False" Grid.Row="1" ItemsSource="{Binding Results}">
<DataGrid.Columns>
<DataGridTextColumn Header="#" Width="20" Binding="{Binding Path=Count}" />
<DataGridTextColumn Header="Name" Width="*" Binding="{Binding Path=ComponentName}" />
<DataGridTextColumn Header="Variable" Width="*" Binding="{Binding Path=Property}" />
<DataGridTextColumn Header="Value" Width="*" Binding="{Binding Path=PropertyValue}" />
<DataGridComboBoxColumn Header="Unit" Width="*" ItemsSource="{Binding Units}"/>
</DataGrid.Columns>
</DataGrid>
ViewModel.cs
private List<ResultModel> _results;
public List<ResultModel> Results
{
get { return _results; }
set
{
_results = value;
RaisePropertyChanged("Results");
}
}
ResultModel.cs
private int _count;
public int Count
{
get { return _count; }
set { _count = value; RaisePropertyChanged("Count"); }
}
private string _componentName;
public string ComponentName
{
get { return _componentName; }
set { _componentName = value; RaisePropertyChanged("ComponentName"); }
}
private string _property;
public string Property
{
get { return _property; }
set { _property = value; RaisePropertyChanged("Property"); }
}
private double _propertyValue;
public double PropertyValue
{
get { return _propertyValue; }
set { _propertyValue = value; RaisePropertyChanged("PropertyValue"); }
}
private List<object> _units;
public List<object> Units
{
get { return _units; }
set { _units = value; RaisePropertyChanged("Units"); }
}
private Type _componentType;
public Type ComponentType
{
get { return _componentType; }
set { _componentType = value; RaisePropertyChanged("ComponentType"); }
}
I had to use a DataGridTemplateColumn that contained a ComboBox to get it to work properly. This assumes the object in Units has a Name property to display, you should adjust DisplayMemberPath accordingly. You will pribably also want to bind SelectedItem to something, so you know what item they picked.
<DataGridTemplateColumn Header="Unit">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate DataType="local:ResultModel">
<ComboBox
DisplayMemberPath="Name"
ItemsSource="{Binding Path=Units}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Try this:
<DataGridComboBoxColumn Header="Unit" Width="*">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Units}" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Units}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
You may also want to set the DisplayMemberPath property of the DataGridComboBoxColumn to the name of a property of the units.

WPF DataGridCell Style binding issue

I'm facing a strange issue binding Collection to DataGrid on which when selecting a row the binding seems to disappear (I have an empty cell)
Here is my object list
public ReadOnlyCollection<ItemPoint> CurrentItemPoints { get; private set; }
ItemPoint object is defined as :
public sealed class ItemPoint : PropertyChangedNotifierBase
{
private bool _IsSubscribed = false;
private string _Name = string.Empty;
private string _Value = string.Empty;
private DateTime _ValueTime = DateTime.UtcNow;
public bool IsSubscribed
{
get { return _IsSubscribed; }
set
{
if (_IsSubscribed != value)
ChangeSubscription(value);
ChangeProperty("IsSubscribed", ref _IsSubscribed, value);
}
}
public string Name
{
get { return _Name; }
private set
{
ChangeProperty("Name", ref _Name, value);
}
}
public string Value
{
get { return _Value; }
set
{
_Value = value;
}
}
public DateTime ValueTime
{
get { return _ValueTime; }
private set
{
ChangeProperty("ValueTime", ref _ValueTime, value);
}
}
}
here is my xaml:
<DataGrid Name="PointsList" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="2,0,0,0"
ItemsSource="{Binding CurrentItemPoints, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding Path=IsSubscribed, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="10">
<DataGridCheckBoxColumn.CellStyle>
<Style>
<EventSetter Event="CheckBox.Checked" Handler="SubscriptionCheckBox_Checked"/>
</Style>
</DataGridCheckBoxColumn.CellStyle>
</DataGridCheckBoxColumn>
<DataGridTextColumn Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" Header="Name" Width="*"/>
<DataGridTextColumn Binding="{Binding Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, IsAsync=True, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" Header="WorkingValueColumn" Width="*"/>
<DataGridTextColumn Binding="{Binding Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, IsAsync=True, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" Header="NonWorkingValueColumn" Width="*">
<DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<ContentPresenter/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Path=ValueTime, UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True, Mode=OneWay, StringFormat='{}{0:dd-MM-yyyy HH:mm:ss.fff}'}" Header="Time" Width="*">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
If I now display the datagrid everything is ok... until I select any cell of the grid.
Doing that I will have the "WorkingValueColumn" working well... meaning that will keep displaying the selected item value while the "NonWorkingValueColumn" will display an empty cell...
Here is a screenshot of part of datagrid as sample:
I've been looking for a while now without finding any kind of explication... I though I could have missed some selection template or something like that but I really don't know.
Thanks for your help!
I finally could workaround that strange behavior changing the DataTextColumn by a DataTemplateColumn as that:
<DataGridTemplateColumn Header="Value">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" HorizontalAlignment="Stretch"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" BorderThickness="0" HorizontalAlignment="Stretch"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>

Data grid display icon on one column

IM using data grid which are filled with data during RT(Im using mvvm).
I bind the data grid to observer collection which is updated during RT with values.
one of the fields are isKey .if this value is true I want to display some icon of key.
how can i do that?
I need to add the icon just when key is true .
this is my code
model
public bool IsKey { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
{
public ViewModel()
{
this.Items = new List<MyClass>();
//row 1:
this.Items.Add(new MyClass { IsKey= true,Column2 = "aaaa",Column3 = "ddfa",Column4 = "fddsfas",Column5 = "dfadsfas"});
//row 2:
this.Items.Add(new MyClass { IsKey = false ,Column2 = "aaaa",Column3 = "ddfa",Column4 = "fddsfas",Column5 = "dfadsfas"});
}
the xaml
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding isKey}" Header="2" Width="*" />
<DataGridTextColumn Binding="{Binding Column2}" Header="2" Width="*" />
<DataGridTextColumn Binding="{Binding Column3}" Header="3" Width="*" />
<DataGridTextColumn Binding="{Binding Column4}" Header="4" Width="*" />
You need DataGridTemplateColumn. Set its CellTemplate to contain ContentControl whose Content will be null in case IsKey value is false and set it to Icon when value is true for IsKey.
<DataGridTemplateColumn IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ContentControl x:Name="content"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsKey}" Value="True">
<Setter TargetName="content" Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Image Source="IconSourcePath" Height="30"/>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Categories