代码之家  ›  专栏  ›  技术社区  ›  GreatSeaSpider

WPF DataGrid绑定DataGridCell内容

  •  4
  • GreatSeaSpider  · 技术社区  · 16 年前

    希望这将是一个非常简单的答案,我只是没有看到俗话所说的“以木代树”。

    我有一个DataGridCell样式,我想将单元格的内容绑定到图像的source属性,下面是我目前使用的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>
    

    提前谢谢!

    皮特

    1 回复  |  直到 16 年前
        1
  •  6
  •   Quartermeister    16 年前

    如果列是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是具有图像路径的行对象的属性。