我是WPF的初学者。
我有一个数据网格,用于显示带有列定义的消息,如下所示。数据网格绑定到数据表
<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>
现在我需要添加带有标题的coulmn作为“状态”。和内容为图像。我有约束力 此列的数据表的“IsRead”列,如果IsRead值为False,则需要显示图像unread.png,如果IsRead值为True,则需要显示图像read.png
我该怎么做?
答案 0 :(得分:11)
您可以在包含绑定属性的类中创建StatusImage属性:
public string StatusImage {
get
{
if (IsRead)
return "read.png";
return "unread.png";
}
}
然后将其绑定到图像,例如:
<Image Source="{Binding StatusImage}"></Image>
或者就像你没有上课一样。您可以在数据触发器之间进行选择:
<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>
或者您可以使用值转换器:
类别:
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();
}
}
窗口资源:
<local:IsReadImageConverter ReadImage="Read.png" UnreadImage="Unread.png" x:Key="BoolImageConverter"/>
然后您的绑定将是:
ImageSource={Binding Path=IsRead,Converter={StaticResource BoolImageConverter}}"
一切都有效。