我在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;
是我发送到要转换为Image的DataGridTextColumn的布尔值。
我希望我足够精确,如果您需要更多信息,我可以编辑我的帖子。
谢谢你的帮助。
你好,
Flo。
方法中的value
inConvert
是要转换的实际值(property的值Flag
)。
因此value as System.Windows.Controls.ListBoxItem
,将返回null
。
改用这个:
if ((bool)value)
{
}
请参阅MSDN上value
的文档中的使用IValueConverter
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句