WPF DataGrid icon and boolean value

喜夏-厌秋 提交于 2019-12-24 00:46:38

问题


I have:

public class Person 
{
   String name { get; set; }
   String address { get; set; } 
   bool isMarried { get; set; } 
}

My datagrid gets populated with a list of persons.

I want to have a custom column where icon-1.jpg is displayed when isMarried is true and icon-2.jpg is displayed when isMarried is false.

How do I do this in WPF ? Any ideas ?

I know how to do a custom column but I do not know how to assoc the two states of isMarried with icon-1.jpg and icon-2.jpg.


回答1:


You could do this with a DataTrigger in your custom column:

<DataGridTemplateColumn Header="Married">
   <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
         <Image x:Name="IMG" Source="married_image" /> 
         <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=isMarried}" Value="False">
               <Setter Property="Source" Value="not_married_image" TargetName="IMG"/>
            </DataTrigger>
         </DataTemplate.Triggers>
      </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>



回答2:


You can use an IValueConveter to convert from a Boolean value to an Uri (Uri is what you need for image source).

public class MarriedConverter : IValueConverter
{
    public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
    {
        if ((value == null) || !(value is bool))
            return null;

        bool isMarried = (bool)value;

        if (isMarried)
            return new Uri(#1);
        else
            return new Uri(#2);
    }

    public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}


来源:https://stackoverflow.com/questions/4045002/wpf-datagrid-icon-and-boolean-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!