WPF数据网格绑定DataGrid单元格内容

5
希望我的回答能简单明了,我认为这只是看不到树木而已。
我有一个DataGridCell样式,在其中我想将单元格的内容绑定到图像的源属性上,以下是我目前使用的XAML代码:
<Style x:Key="DataGridImageCellStyle" TargetType="{x:Type toolkit:DataGridCell}">
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="BorderBrush" Value="Transparent" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type toolkit:DataGridCell}">
                <Border Background="Transparent" 
              BorderBrush="{TemplateBinding BorderBrush}"  
              BorderThickness="0" 
              SnapsToDevicePixels="True">
                    <Image Source="{Binding RelativeSource={RelativeSource AncestorType=toolkit:DataGridCell}, Path=Content}" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

请注意,目前我正在将图像源绑定到Content上..这不起作用,我也尝试了Value,但也不起作用!
所以我的问题很简单..使用什么正确的绑定方式可以将单元格内容放入此图像的源属性中?
提前感谢!
Pete
1个回答

6
如果该列是DataGridTextColumn,那么您可能可以绑定到其内容中的TextBlock的Text属性:
<Image Source="{Binding RelativeSource=
     {RelativeSource AncestorType=DataGridCell}, Path=Content.Text}" />

虽然这真的是一个技巧,但如果您想在列中显示图像,则应该使用DataGridTemplateColumn

<DataGridTemplateColumn Header="...">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Image Source="{Binding SomeProperty}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

其中 SomeProperty 是您的行对象具有图像路径的属性。


谢谢您的回复,最终我选择了一种方法来避免再花费更多时间!顺便问一下...如果我使用DataGridTemplateColumn,考虑到单元格绑定到DataTableRow中的单元格,您会期望绑定路径是什么?再次感谢! - GreatSeaSpider
@GreatSeaSpider:我认为当你绑定到一个 DataTable 时,你应该使用 DataColumn.ColumnName 值作为绑定路径。 - Quartermeister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接