How to change WPF datagrid row image depending on binding value
I am getting started with WPF.
I have a data grid to display messages with column definitions as shown below. Data grid is bound to datatable
<my:DataGridTextColumn Binding="{Binding Module}" Header="Module"
Width="75" IsReadOnly="True"></my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding Record ID}" Header="RecordID"
Width="75" IsReadOnly="True"></my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding ItemName}"
Header="Item/Platform/Country Name" Width="175" IsReadOnly="True">
</my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding DateReceived}"
Header="DateReceived" Width="150" IsReadOnly="True">
</my:DataGridTextColumn>
<my:DataGridTextColumn Binding="{Binding Comments}" Header="Comments"
Width="300" IsReadOnly="True"></my:DataGridTextColumn>
Now I need to add coulmn with title as "Status". and content as an image. I am required Column "IsRead" of data related to this column, so if IsRead is False, I need to show the unread.png image, and if IsRead is True, I need to show the read.png image
How should I do it?
+3
source to share
1 answer
You can create a StatusImage property in the class that contains your binding properties:
public string StatusImage {
get
{
if (IsRead)
return "read.png";
return "unread.png";
}
}
And then bind it to an image, for example:
<Image Source="{Binding StatusImage}"></Image>
Or as in your case, if you don't have a class. You can choose between datatrigger:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Name="IsReadImage" Source="read.png"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsRead}" Value="False">
<Setter TargetName="IsReadImage" Property="Source" Value="unread.png"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Or you can use a value converter:
Class:
public class IsReadImageConverter : IValueConverter
{
public Image ReadImage { get; set; }
public Image UnreadImage { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is bool))
{
return null;
}
bool b = (bool)value;
if (b)
{
return this.ReadImage
}
else
{
return this.UnreadImage
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Window resources:
<local:IsReadImageConverter ReadImage="Read.png" UnreadImage="Unread.png" x:Key="BoolImageConverter"/>
Then your binding will be:
ImageSource={Binding Path=IsRead,Converter={StaticResource BoolImageConverter}}"
Should everyone work.
+10
source to share