绑定到DataContext的WPF Style DataTrigger不起作用

问题描述 投票:14回答:1

我有一个TextBox,其样式有一个DataTrigger,用于更改文本,如下所示:

<Grid>
    <TextBlock Text="Foo">
        <TextBlock.Style>
            <Style BasedOn="{StaticResource TextStyle}" TargetType="TextBlock">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding MyBool}" Value="True">
                        <Setter Property="Text" Value="Bar"/>
                    </DataTrigger>
                 </Style.Triggers>
             </Style>
         </TextBlock.Style>
     </TextBlock>
</Grid>

但它不起作用,文本永远不会变为“Bar”。我已经使用Text =“{Binding MyBool}”测试了另一个TextBlock,此文本从“False”变为“True”。 Snoop没有发现我能看到的错误,输出中没有任何内容。

这个问题可能看起来像WPF Trigger binding to MVVM property的重复,但我的代码似乎与那里接受的答案(http://www.thejoyofcode.com/Help_Why_cant_I_use_DataTriggers_with_controls_in_WPF.aspx,“使用风格”部分)没有任何相关的方式。并且在实际答案中建议使用DataTemplate似乎是错误的,因为我只想将它应用于单个TextBlock,但如果它是正确的,我不知道如何为此编写DataTemplate ...

编辑:

这就是我绑定的属性看起来像:

public bool MyBool
{
    get { return _myBool; }
    set
    {
        if (_myBool== value)
            return;

        _myBool= value;
        NotifyPropertyChanged();
    }
}
private bool _myBool;
c# wpf binding datatrigger
1个回答
54
投票

可以从许多不同的地方设置依赖属性;内联,动画,强制,触发器等。因此创建了一个Dependency Property Value Precedence列表,这决定了哪些更改覆盖了其他更改。由于这种优先顺序,我们不能使用Trigger来更新在XAML中明确设置为内联的属性。试试这个:

<Grid>
    <TextBlock>
        <TextBlock.Style>
            <Style BasedOn="{StaticResource TextStyle}" TargetType="TextBlock">
                <!-- define your default value here -->
                <Setter Property="Text" Value="Foo" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding MyBool}" Value="True">
                        <!-- define your triggered value here -->
                        <Setter Property="Text" Value="Bar" />
                    </DataTrigger>
                 </Style.Triggers>
             </Style>
         </TextBlock.Style>
     </TextBlock>
</Grid>
© www.soinside.com 2019 - 2024. All rights reserved.