我有一个数据绑定是数据绑定,但在绑定发生之前,我使用datagrid loadingrow事件处理程序根据遇到的条件为每行的背景着色。我想删除它,我已经决定将datatemplatecolumn(STATUS)添加到未绑定的datagrid但我希望根据使用LoadingRow事件遇到的条件填充适当的图像。我没有使用DataTemplate的原因是由于确定正确的iamge所需的日期比较。
我查看了几个示例,但不知道如何将图像添加到“状态”列上的单元格中以包含每行的图像。我非常感谢你的指导。
感谢您一如既往的帮助,
XAML
<DataGrid AutoGenerateColumns="False" x:Name="schDataGrid" IsReadOnly="True" LoadingRow="schDataGrid_LoadingRow" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="STATUS" /> <-- Add Image Here -->
<DataGridTextColumn Binding="{Binding ITEMNUMBER}" Header="ITEMNUMBER" />
<DataGridTextColumn Binding="{Binding CODE}" Header="CODE" />
<DataGridTextColumn Binding="{Binding DESC}" Header="STD DESCRIPTION" />
<DataGridTextColumn Binding="{Binding DESCRIPTION}" Header="UNIQUE DESCRIPTION" />
<DataGridTextColumn Binding="{Binding SERIALNUMBER}" Header="SERIAL NUMBER" />
</DataGrid.Columns>
</DataGrid>
C#
private void schDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
var row = e.Row;
DataRowView rView = row.Item as DataRowView;
string DUEDATE = rView["DUEDATE"].ToString();
DateTime now = Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"));
DateTime compareDate = Convert.ToDateTime(DUEDATE);
TimeSpan difference = now - compareDate;
if (difference.Days <= 0)
{
Image image = new Image();
var uriSource = new Uri(@"/main;component/Images/Icons/green.gif", UriKind.Relative);
image.Source = new BitmapImage(uriSource);
//Now Add the image to the DataGridTemplateColumn["STATUS"]
rItem["STATUS"] = image;
}
答案 0 :(得分:0)
如果状态是您绑定到网格的同一对象的一部分,您仍然可以使用DataTemplate:
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Status, Converter={StaticResource StatusToImageConvertor}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
在您的XAML资源中包含转换器的参考:
<converter:StatusToImageConvertor:Key="StatusToImageConvertor"/>
这就是你的转换器的样子:
public sealed class StatusToImageConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// The value here is your status being passed from XAML binding
if (value is string)
{
if(value == "x") return "image1.png";
if(value = "y") return "image2.png";
else return "image3.png";
}
else return string.empty;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
如果这有助于你,请告诉我