views:

1770

answers:

2

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?

A: 

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.

Brad Leach
There is a 4th solution: TemplateSelectors
bitbonk
+2  A: 

There are three common techniques for this.

1) DataTrigger:

<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>

2) ValueConverters:

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;
        }
    }
}

3) MVVM (Model-View-ViewModel):

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>
Josh G