我在DataGridTextColumn上有一个布尔值,如果图像为True,我想打印图像,如果图像为假,我想打印另一个图像。
这是DataGrid:
<DataGrid x:Name="DonneesBrutes" IsReadOnly="True" ItemsSource="{Binding Path=ResultatCollectionGrande}" Margin="10,65,0,0" AutoGenerateColumns="False" EnableRowVirtualization="True" RowDetailsVisibilityMode="VisibleWhenSelected">
<DataGrid.Columns>
<DataGridTextColumn x:Name="PrisEnCompte" Width="50" Binding="{Binding Path=Flag,Converter={StaticResource BoolImageConverter}}" Header="PEC"></DataGridTextColumn>
这是Windows.Resources,我在其中定义了转换器以及使用了哪些图像:
<Window.Resources>
<Image x:Key="TrueImage" Source="booleanTrue.png"/>
<Image x:Key="FalseImage" Source="booleanFalse.png"/>
<local:BoolToImage TrueImage="{StaticResource TrueImage}" FalseImage="{StaticResource FalseImage}" x:Key="BoolImageConverter"/>
</Window.Resources>
还有转换器:
public class BoolToImage : IValueConverter
{
public Image TrueImage { get; set; }
public Image FalseImage { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var viewModel = (ViewModel)(value as System.Windows.Controls.ListBoxItem).DataContext;
if (!(value is bool))
{
return null;
}
bool b = (bool) viewModel.ActiviteCollection.FirstOrDefault().Flag;
if (b)
{
return this.TrueImage;
}
else
{
return this.FalseImage;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
当我宣布我的var viewModel
时出现错误the reference object is not set to an instance of an object
我认为声明(value as System.Windows.Controls.ListBoxItem)
是错误的,但我找不到如何更正此
精度viewModel.ActiviteCollection.FirstOrDefault().Flag;
是我发送给DataGridTextColumn的布尔值,我希望将其转换为Image。
我希望我足够精确,如果您需要更多信息,我可以编辑我的帖子。
感谢您的帮助。
问候,
弗洛。
答案 0 :(得分:2)
value
方法中的Convert
是要转换的实际值(属性Flag
的值)。
因此,value as System.Windows.Controls.ListBoxItem
将返回null
。
请改用:
if ((bool)value)
{
}
请参阅MSDN上IValueConverter
文档中value
的使用情况。