[英]Binding to simple properties in WPF DataGrid
I've got a problem binding to a property on my model. 我绑定到模型上的属性时遇到问题。 In a DataGrid, I'm displaying Errors.
在DataGrid中,我正在显示错误。 Each error has the property
ErrorDescription
which itself has the property Severity
. 每个错误都具有属性
ErrorDescription
,其本身具有属性Severity
。
I can bind to Severity
in the TextColumn of my DataGrid below, however binding to Severity
in the TemplateColumn fails with the error 我可以绑定到
Severity
在我下面的DataGrid的TextColumn,但是结合Severity
在TemplateColumn中失败,出现错误
"Cannot resolve property "ErrorDescription" in data context of type MainViewModel"
“在MainViewModel类型的数据上下文中无法解析属性“ ErrorDescription””
The DataContext my image-column is not the same as in my first text-column. DataContext我的图像列与我的第一个文本列不同。 Why is that?
这是为什么?
<DataGrid ItemsSource ="{Binding Errors}" AutoGenerateColumns="False">
<DataGrid.Columns>
// works
<DataGridTextColumn Binding="{Binding ErrorDescription.Severity}"></DataGridTextColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image>
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
// Binding fails
<DataTrigger Binding="{Binding ErrorDescription.Severity}" Value="Unknown">
<Setter Property="Source" Value="/error.jpg"/>
</DataTrigger>
// Binding fails
<DataTrigger Binding="{Binding ErrorDescription.Severity}" Value="Ok">
<Setter Property="Source" Value="/ok.jpg"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
What about using a Converter instead of DataTrigger? 如何使用Converter而不是DataTrigger? When I want to show icons or specific property values depending an enum I do it with a Converter.
当我想根据枚举显示图标或特定属性值时,可以使用Converter。
The Converter would be similar to this: 转换器将类似于以下内容:
public class ErrorSeverityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Severity severity = (Severity)value;
switch(severity)
{
case Severity.Unknown:
return "/error.jpg";
case Severity.Ok:
return "/ok.jpg";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
There is this other question that is very similar even if not on a DataGridTemplateColumn 即使没有在DataGridTemplateColumn上,还有另一个非常相似的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.