简体   繁体   中英

WPF: How to swap Listview cell content with a datatrigger (or equivalent)

I have a WPF App that implements a ListView. I would like to show an image (a small icon) in one of the columns depending on the type of the data that row represents. Sort of like the display you see in Windows Explorer.

I am using DataTriggers elsewhere in my XAML, it seems like a similar method could be used to swap out entire cell contents, but I can't find an example of anyone doing that.

Any thoughts?

There are three common techniques for this.

<DataTemplate x:Key="ImageColumn">
    <Grid>
        <Image x:Name="img" Source="MyImage.png"/>
        <Rectangle x:Name="rect" Fill="Red" Visibility="Hidden"/>
    </Grid>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding TriggerProperty}" Value="2">
            <Setter TargetName="rect" Property="Visibility" Value="Visible"/>
            <Setter TargetName="img" Property="Visibility" Value="Hidden"/>
        </DataTrigger>
        <!--etc...-->
    </DataTemplate.Triggers>
</DataTemplate>

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string strVal = value as string;
        switch (strVal)
        {
            case "2":
                Rectangle rect = new Rectangle();
                rect.Fill = Brushes.Red;
                return rect;

            default:
                Image img = new Image();
                ImageSourceConverter s = new ImageSourceConverter();
                img.Source = (ImageSource)s.ConvertFromString("MyImage.png");
                return img;
        }
    }
}

Create a ViewModel class that wraps your data model. This ViewModel would evaulate the properties in the data model and combine them with logic into a new property.

public UIElement Icon
{
    get
    {
        if (TriggerProperty == "2")
        {
            Rectange rect = new Rectangle();
            rect.Fill = Brushes.Red;
            return rect;
        }

        else
        {
            Image img = new Image();
            ImageSourceConverter s = new ImageSourceConverter();
            img.Source = (ImageSource)s.ConvertFromString("MyImage.png");
            return img;
        }
    }
}

And the XAML:

<DataTemplate x:Key="ImageColumn">
    <ContentControl Content="{Binding Icon}"/>
</DataTemplate>

In the past, I've used ValueConverters to provide the Image I want to display, however I am intrigued to the possibility of using DataTriggers for this purpose.

Beatriz Stollnitz posts a solution to a similar issue here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM