合并Style.Triggers与WPF中的属性模板

时间:2014-03-01 17:38:40

标签: wpf

我想为我的DataGrid设置样式,但我不知道问题出在哪里 在存在Template属性的情况下,backgroud属性不能与其值一起使用。

我的代码:

    <Style x:Key="DataGridStyle1" TargetType="{x:Type DataGrid}">
        <Setter Property="CellStyle" Value="{DynamicResource GridStyle1}"/>
    </Style>

    <Style x:Key="GridStyle1" TargetType="DataGridCell">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True" >
                <Setter Property="Background" Value="SeaGreen"/>
            </Trigger>
        </Style.Triggers>
        <Style.Setters>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type DataGridCell}">
                    <Border Name="DataGridCellBorder">
                        <ContentControl Content="{TemplateBinding Content}">
                            <ContentControl.ContentTemplate>
                                <DataTemplate>
                                    <TextBlock Background="Transparent" TextWrapping="WrapWithOverflow" TextTrimming="CharacterEllipsis" 
                            Height="auto" Width="auto" Text="{Binding Text}"/>
                                </DataTemplate>
                            </ContentControl.ContentTemplate>
                        </ContentControl>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        </Style.Setters>
    </Style>

请帮帮我。

1 个答案:

答案 0 :(得分:1)

明确将TextBlock背景设置为透明,因此它不会从DataGridCell中选择值。您应该使用RelativeSource绑定DataGridCell的背景,如下所示:

<TextBlock Background="{Binding Background, RelativeSource={RelativeSource 
                                Mode=FindAncestor, AncestorType=DataGridCell}}"
           TextWrapping="WrapWithOverflow" TextTrimming="CharacterEllipsis"
           Height="auto" Width="auto" Text="{Binding Text}"/>
相关问题