我有一个 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 触发器绑定到 MVVM 属性 https://stackoverflow.com/questions/1795476/wpf-trigger-binding-to-mvvm-property,但我的代码似乎与那里接受的答案没有什么不同(http://www.thejoyofcode.com/Help_Why_cant_I_use_DataTriggers_with_controls_in_WPF.aspx http://www.thejoyofcode.com/Help_Why_cant_I_use_DataTriggers_with_controls_in_WPF.aspx,“使用样式”部分)以任何相关方式。并且按照实际答案中的建议使用 DataTemplate 似乎是错误的,因为我只想将其应用于单个 TextBlock,但如果它是正确的,我不确定如何为此编写 DataTemplate...
EDIT:
这就是我绑定的属性的样子:
public bool MyBool
{
get { return _myBool; }
set
{
if (_myBool== value)
return;
_myBool= value;
NotifyPropertyChanged();
}
}
private bool _myBool;
依赖属性可以从许多不同的地方设置;内联、动画、强制、触发器等。依赖属性值优先级 https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)