绑定到DataContext的WPF样式DataTrigger不起作用 [英] WPF Style DataTrigger with binding to DataContext not working
问题描述
我有一个文本框,其样式具有更改文本的DataTrigger,如下所示:
I have a TextBox with a style that has a DataTrigger which changes the text, like this:
<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".我已经测试过将另一个TextBlock与Text ="{Binding MyBool}"一起使用,并且此文本从"False"更改为"True". Snoop没有发现我可以看到的错误,并且输出中没有任何内容.
But it's not working, the text never changes to "Bar". I have tested using another TextBlock with Text="{Binding MyBool}" and this text changes from "False" to "True". Snoop reveals no errors that I can see and there is nothing in the output.
这个问题似乎与 WPF触发器绑定到MVVM属性 >,但我的代码似乎与此处接受的答案没有什么不同( http://www.thejoyofcode.com/以任何相关方式查看Help_Why_cant_I_use_DataTriggers_with_controls_in_WPF.aspx ,使用样式"部分.并按照实际答案中的建议使用DataTemplate似乎是错误的,因为我只希望将其应用于单个TextBlock,但是如果正确,我不确定如何为此编写DataTemplate ...
This question may seem like a duplicate of WPF Trigger binding to MVVM property, but my code does not seem different from the accepted answer there (http://www.thejoyofcode.com/Help_Why_cant_I_use_DataTriggers_with_controls_in_WPF.aspx, section "Using a style") in any relevant way. And using a DataTemplate as suggested in the actual answer seems wrong since I only want this to apply to a single TextBlock, but if it is correct, I'm not sure how to write a DataTemplate for this...
这就是我要绑定的属性的样子:
This is what the property I'm binding to looks like:
public bool MyBool
{
get { return _myBool; }
set
{
if (_myBool== value)
return;
_myBool= value;
NotifyPropertyChanged();
}
}
private bool _myBool;
推荐答案
依赖项属性可以在许多不同的地方进行设置;内联,动画,强制,触发器等.例如
Dependency Properties can be set from many different places; inline, animations, coercion, triggers, etc. As such a Dependency Property Value Precedence list was created and this dictates which changes override which other changes. Because of this order of precedence, we can't use a Trigger
to update a property that is explicitly set inline in your XAML. Try this instead:
<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>
这篇关于绑定到DataContext的WPF样式DataTrigger不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!