Kamal Rathnayake
Kamal Rathnayake

Reputation: 582

WPF Data binding and Image

I have this Xaml code

<ListView x:Name="listOrderList" Margin="58,55,0,0" Background="{x:Null}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="DESCRIPTION" DisplayMemberBinding="{Binding Description}"/>
            <GridViewColumn Header="STATUS">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="{Binding Status}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

In C# I have an enum for Status and i know obviously <Image Source="{Binding Status}"/> is not going to work. But how can do something for example i have two values in Status enum. Say Yes and No. How can i assign small icons to enum's values and work with Bindings easily.

Thanks you.

Upvotes: 0

Views: 1173

Answers (3)

Avinash Singh
Avinash Singh

Reputation: 2785

You can set Icon image path to Enum, then Bind DataGrid with that Enum.

            <DataGridTemplateColumn x:Name="colStatus" Width="160" Header="Status">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                   <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" OverridesDefaultStyle="True" Width="135">
                                    <Image Height="14" Margin="2,0,0,0" HorizontalAlignment="Left" Source="{Binding Status}" Width="14" />
                                    </StackPanel>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>

Upvotes: 1

Clemens
Clemens

Reputation: 128013

Either you use a binding converter, or you add DataTriggers to your DataTemplate. The example below assumes the following enum

public enum Status { Status1, Status2 }

and sets the Image's Source property to different image resources depending on the value of the Status property.

<Window.Resources>
    <BitmapImage x:Key="Image1" UriSource="..."/>
    <BitmapImage x:Key="Image2" UriSource="..."/>
</Window.Resources>

...

<DataTemplate>
    <Image x:Name="image"/>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Status}" Value="Status1">
            <Setter TargetName="image" Property="Source"
                    Value="{StaticResource Image1}"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding Status}" Value="Status2">
            <Setter TargetName="image" Property="Source"
                    Value="{StaticResource Image2}"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

Upvotes: 2

Felix C
Felix C

Reputation: 1775

Check out IValueConverter

With that you can check which value was delivered by the binding and then create the Image object to display.

Upvotes: 2

Related Questions