WPF 数据触发器未按预期触发
我有以下 XAML:
<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/>
<TextBlock Text="items selected">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
<Setter Property="TextBlock.Text" Value="item selected"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
第一个文本块愉快地随 SelectedItems.Count 变化,显示 0,1,2 等。第二个块上的数据触发器似乎永远不会触发来更改文本。
有什么想法吗?
I have the following XAML:
<TextBlock Text="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Margin="0,0,5,0"/>
<TextBlock Text="items selected">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EditListBox, Path=SelectedItems.Count}" Value="1">
<Setter Property="TextBlock.Text" Value="item selected"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
The first text block happily changes with SelectedItems.Count, showing 0,1,2, etc. The datatrigger on the second block never seems to fire to change the text.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者,您可以用以下内容替换您的 XAML:
转换器可以解决许多绑定问题,但拥有大量专用转换器会变得非常混乱。
Alternatively, you could replace your XAML with this:
Converters can solve a lot of binding problems but having a lot of specialized converters gets very messy.
DataTrigger 正在触发,但第二个 TextBlock 的文本字段被硬编码为“选定的项目”,因此无法更改。 要查看它的触发,您可以删除 Text="items selected"。
您的问题很适合使用 ValueConverter 而不是 DataTrigger。 以下是如何创建和使用 ValueConverter 来将 Text 设置为您想要的内容。
创建此 ValueConverter:
将命名空间引用添加到转换器所在的程序集:
将转换器添加到您的资源:
更改您的第二个文本块:
The DataTrigger is firing but the Text field for your second TextBlock is hard-coded as "items selected" so it won't be able to change. To see it firing, you can remove Text="items selected".
Your problem is a good candidate for using a ValueConverter instead of DataTrigger. Here's how to create and use the ValueConverter to get it to set the Text to what you want.
Create this ValueConverter:
Add the namespace reference to your the assembly the converter is located:
Add the converter to your resources:
Change your second textblock to: