如何基于DataGrid单元格值加载不同的图像?

时间:2018-08-11 17:38:14

标签: wpf xaml

假设我有一个DataGrid,其单元格包含默认图像:

<Datagrid AutoGenerateColumns="False"                                  ItemsSource="{Binding}">
<DataGrid.Columns>
 <DataGridTextColumn Header="Bookmaker" Binding="{Binding book_name}"/>
   <DataGridTemplateColumn CanUserResize="False">
     <DataGridTemplateColumn.CellTemplate>
       <DataTemplate>
         <Image Source="/App;component/Resources/Assets/foo.png" Width="40" Height="40"
         Stretch="UniformToFill" StretchDirection="Both"
         RenderOptions.BitmapScalingMode="HighQuality" />
         <DataTemplate.Triggers>
         <DataTrigger Binding="{Binding book_name}" Value="test">
         <Setter Property="sour" /> ????
     </DataTrigger>
     </DataTemplate.Triggers>
   </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

我希望显示为默认图像foo.png,但是如果单元格的值包含test,则需要更改图像的来源,但是找不到任何Source属性,因为我使用DataTemplate,有人遇到过类似情况吗?

1 个答案:

答案 0 :(得分:2)

设置样式Image并使用该样式内的触发器为图像选择Source

<DataTemplate>
    <Image Width="40" Height="40"
           Stretch="UniformToFill" StretchDirection="Both"
           RenderOptions.BitmapScalingMode="HighQuality">
        <Image.Style>
            <Style TargetType="Image">
                <Setter Property="Source" Value="pack://application:,,,/Assets/foo.png" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding book_name}" Value="test">
                        <Setter Property="Source" Value="pack://application:,,,/Assets/bar.png" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>
</DataTemplate>