How to change the image of WPF datagrid row depending on binding value

跟風遠走 提交于 2019-12-01 09:04:22

You could create a StatusImage property in the class that holds your binding properties:

public string StatusImage {
    get 
    {
        if (IsRead)
            return "read.png";
        return "unread.png";
    }
}

And then bind it to the image for example:

<Image Source="{Binding StatusImage}"></Image>

Or as in your case that you haven't got a class. You could choose between a datatrigger:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Image Name="IsReadImage" Source="read.png"/>
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding IsRead}" Value="False">
                    <Setter TargetName="IsReadImage" Property="Source" Value="unread.png"/>
                </DataTrigger>             
            </DataTemplate.Triggers>         
        </DataTemplate>     
    </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

Or you could use a value converter:

Class:

public class IsReadImageConverter : IValueConverter  
{
    public Image ReadImage { get; set; }
    public Image UnreadImage { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is bool))
        {
            return null;
        }
        bool b = (bool)value;
        if (b)
        {
            return this.ReadImage
        }
        else
        {
            return this.UnreadImage
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Window Resources:

<local:IsReadImageConverter ReadImage="Read.png" UnreadImage="Unread.png" x:Key="BoolImageConverter"/>

Then your binding would be:

ImageSource={Binding Path=IsRead,Converter={StaticResource BoolImageConverter}}"

Should all work.

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