WPF-如何结合使用DataTrigger和Trigger? [英] WPF - How to combine DataTrigger and Trigger?
问题描述
注意我问了一个相关的问题:如何结合使用DataTrigger和EventTrigger?
NOTE I have asked the related question: How to combine DataTrigger and EventTrigger?
我有一个包含多个项目的列表框。该项目的类实现 INotifyPropertyChanged
并具有属性 IsAvailable
。我使用该属性使用不同的颜色指示列表中的不可用选项。
I have a list box containing several items. The item's class implements INotifyPropertyChanged
and has a property IsAvailable
. I use that property to indicate unavailable options in the list using a different colour.
但是,如果所选项目不可用,则前景色应为红色。 / p>
However, if a selected item is not available, then the foreground colour should be red.
<ListBox>
<ListBox.Resources>
<DataTemplate DataType="{x:Type local:InstitutionViewModel}">
<TextBlock Name="Name" Text="{Binding Name}"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsAvailable}" Value="False">
<Setter TargetName="Name" Property="Foreground" Value="#888"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.Resources>
</ListBox>
我使用上述数据触发器将不可用的项目显示为灰色。
I use the above data trigger to grey out unavailable items.
我面临的问题是,选择项目的事实与模板绑定到的基础数据无关。我真正想要的是一种多重触发,它同时支持依赖项属性( ListBoxItem.IsSelected
Trigger >)以及绑定数据项上的 DataTrigger
。
The problem I'm facing is that the fact that the item is selected has nothing to do with the underlying data to which the template is bound. What I really want is some kind of multi-trigger that supports both a regular Trigger
on a dependency property (ListBoxItem.IsSelected
) along with a DataTrigger
on the bound data item.
是否可以做到这一点而无需引入选择的概念进入我的视图模型?
Can this be done without introducing the concept of selection into my view model?
对于想知道为什么我不禁用不可用项的任何人,请理解应用程序的要求是必须选择不可用选项。实际上有几个列表框,其中一个效果的选择在其他效果中可用。我无法禁用这些项目,因为如果根据先前的选择禁用了这些项目,用户将无法改变主意或探索其他组合。
推荐答案
对于其他遇到此问题的人,我找到了适合我的解决方案。当然,我仍然很想看到其他有趣的答案。
For anyone else who's up against this problem, I found a solution that works for me. Of course, I'm still interested to see other interesting answers.
这就是我所做的:
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding
RelativeSource={
RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}},
Path=IsSelected}" Value="True"/>
<Condition Binding="{Binding IsAvailable}" Value="False"/>
</MultiDataTrigger.Conditions>
<Setter TargetName="Name" Property="Foreground" Value="#F00"/>
</MultiDataTrigger>
尽管这是一个多重触发,但并没有什么特别的。如果您只是想在数据模板中为所选项目设置不同的样式,则可以使用:
There's nothing special about this being a multi trigger though. If you just wanted to style the selected item differently in your data template, you could use:
<DataTrigger Binding="{Binding
RelativeSource={
RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}},
Path=IsSelected}" Value="True">
<Setter TargetName="Name" Property="Foreground" Value="#888"/>
</DataTrigger>
这篇关于WPF-如何结合使用DataTrigger和Trigger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!