wpf 如何在属性触发器触发时设置视图模型属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18473625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a viewmodel property when Property Trigger fires
提问by Mike Caron
I have a ListView with a View Model. The ItemsSource is a collection of objects in the View Model. A property exists on the View Model for some flag, IsFlagOn. I want to set that property in the View Model to True when the ListViewItem detects a IsMouseOver. Other UI elements are then bound to this same property so that the view changes as MouseOver is toggled.
我有一个带有视图模型的 ListView。ItemsSource 是视图模型中的对象集合。视图模型上存在某个标志的属性 IsFlagOn。当 ListViewItem 检测到 IsMouseOver 时,我想将该属性在视图模型中设置为 True。然后其他 UI 元素绑定到相同的属性,以便在切换 MouseOver 时视图发生变化。
How would I accomplish this in XAML?
我将如何在 XAML 中完成此操作?
I would imagine something like this (but this breaks):
我会想象这样的事情(但这会中断):
<Style> <!-- on the ListViewItem -->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="DataContext.IsFlagOn" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
UPDATE:
更新:
The error is
错误是
Cannot resolve the Style Property 'IsFlagOn'. Verify that the owning type is the Style's TargetType, or use Class.Property syntax to specify the Property.
无法解析样式属性“IsFlagOn”。验证拥有的类型是 Style 的 TargetType,或使用 Class.Property 语法来指定 Property。
UPDATE(2):
更新(2):
Here's a bit more of the existing XAML (following). You can see that the ListView is bound with a property of the VM, AllItems. Important to note that each item in the list is a VM, where each column is bound. So is the ItemContainerStyle binding against the ListView VM or the Item VM?
这是现有 XAML 的更多内容(如下)。可以看到 ListView 绑定了 VM 的一个属性,AllItems。需要注意的是,列表中的每一项都是一个 VM,其中的每一列都是绑定的。那么 ItemContainerStyle 绑定是针对 ListView VM 还是 Item VM?
<ListView Itemssource="{Binding AllItems}">
<ListView.ItemContainerStyle>
<Style> <!-- on the ListViewItem -->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="DataContext.IsFlagOn" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<!-- ... -->
</GridView>
</ListView.View>
</ListView>
采纳答案by Adi Lester
This is pretty much what OneWayToSourcebinding mode was made for - being able to just update the view model from the view. However, since IsMouseOveris a read-only property, you won'tbe able to do this (due to a bug in WPF):
这几乎就是OneWayToSource绑定模式的目的 - 能够仅从视图更新视图模型。但是,由于IsMouseOver是只读属性,您将无法执行此操作(由于 WPF 中的错误):
<Setter Property="IsMouseOver" Value="{Binding Path=IsFlagOn, Mode=OneWayToSource}" />
There are ways to get around it though. Some of them are described here: OneWayToSource binding from readonly property in XAML
有办法绕过它。其中一些描述如下:OneWayToSource binding from readonly property in XAML

