I have a boolean on a DataGridTextColumn and I want to print an image if it's True and another image if it's False.
This is the 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>
This is the Windows.Resources, where I define the converter and which images are used:
<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>
And there is the converter:
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();
}
}
When I declare my var viewModel
I have the error the reference object is not set to an instance of an object
I think it's the declaration (value as System.Windows.Controls.ListBoxItem)
which is wrong, But I don't find how to correct this.
A precision, viewModel.ActiviteCollection.FirstOrDefault().Flag;
is the boolean I send to the DataGridTextColumn I want to convert as Image.
I hope I'm precise enough, I can edit my post if you need more informations.
Thanks for your help.
Greetings,
Flo.