数据触发器绑定未按预期工作

时间:2012-06-06 16:00:12

标签: wpf xaml data-binding wpf-controls

我有一个为内容控件定义模板的样式....

对于所有控件,它的内容属性为null,我想显示一个文本说控件是空的.....但下面的xaml不起作用,有人知道为什么吗?

        <Style TargetType="ContentControl" x:Key="style">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Content, RelativeSource={RelativeSource Self}}" Value="{x:Null}">
                    <Setter Property="ContentControl.Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                                    <TextBlock Background="Blue">EMPTY!</TextBlock>
                                </Grid>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>

<ContentControl Content="{x:Null}" Style="{StaticResource style}" />

它没有向我显示'EMPTY!'文字。

TKS, 威廉

3 个答案:

答案 0 :(得分:2)

您的代码可以正常工作。带上您的GUI设计师并将其抛到窗外。

答案 1 :(得分:1)

以下作品:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">    
    <Window.Resources>
    <Style TargetType="ContentControl" x:Key="style">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=Content, RelativeSource={RelativeSource Self}}" Value="{x:Null}">
                <Setter Property="ContentControl.Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                                <TextBlock Background="Blue">EMPTY!</TextBlock>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>     
    </Window.Resources>
    <Grid>
        <ContentControl Content="{x:Null}" Style="{StaticResource style}" />
    </Grid>
</Window>

答案 2 :(得分:-1)

只需将文本块值从上下文更改为属性text =“empty”,如

  <TextBlock Background="Blue" Text="Empty"></TextBlock>

enter image description here