gpt4 book ai didi

c# - 如何在 Property Trigger 触发时设置 viewmodel 属性

转载 作者:可可西里 更新时间:2023-11-01 09:10:10 24 4
gpt4 key购买 nike

我有一个带有 View 模型的 ListView。 ItemsSource 是 View 模型中对象的集合。某些标志 IsFlagOn 的 View 模型上存在一个属性。当 ListViewItem 检测到 IsMouseOver 时,我想将 View 模型中的该属性设置为 True。然后将其他 UI 元素绑定(bind)到同一属性,以便在切换 MouseOver 时 View 发生变化。

我如何在 XAML 中完成此操作?

我会想象这样的事情(但这会中断):

<Style> <!-- on the ListViewItem -->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="DataContext.IsFlagOn" Value="True" />
</Trigger>
</Style.Triggers>
</Style>

更新:

错误是

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.

更新(2):

这是现有 XAML 的更多内容(如下)。您可以看到 ListView 与 VM 的属性 AllItems 绑定(bind)。重要的是要注意列表中的每个项目都是一个 VM,其中每一列都是绑定(bind)的。那么 ItemContainerStyle 是针对 ListView VM 还是 Item VM 绑定(bind)的?

<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>

最佳答案

这几乎就是 OneWayToSource 绑定(bind)模式的用途 - 能够仅从 View 更新 View 模型。但是,由于 IsMouseOver 是只读属性,您将无法执行此操作(由于 WPF 中的错误):

<Setter Property="IsMouseOver" Value="{Binding Path=IsFlagOn, Mode=OneWayToSource}" />

虽然有一些方法可以解决这个问题。其中一些描述如下:OneWayToSource binding from readonly property in XAML

关于c# - 如何在 Property Trigger 触发时设置 viewmodel 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18473625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com