gpt4 book ai didi

WPF。更改事件绑定(bind)上的 DataContext 以访问 MVVM 项目的代码隐藏

转载 作者:行者123 更新时间:2023-12-03 10:27:48 25 4
gpt4 key购买 nike

我正在使用 MVVM 开发 WPF 应用程序。
在 XAML 代码中,我有一个网格,其 DataContext 指向 ViewModel,我需要知道是否可以在运行时更改 DataContext 以在其代码隐藏处访问事件。

View 的代码隐藏:

public partial class MainWindow : Window
{
public MainWindow()
{
this.DataContext = new MainViewModel();
InitializeComponent();
}

private void ValidationEvent(object sender, ValidationErrorEventArgs e)
{
//Something useful
}
}

这是我在 XAML 中尝试的代码:
<Grid Validation.Error={Binding Path=ValidationEvent RelativeSource={RelativeSource Self}}/>

XAML 代码会引发 XamlParseException,告知无法对“AddErrorHandler”进行绑定(bind),只能对 DependencyObject 进行 DependencyProperty。

我不想更改 Grid 的 DataContext,因为其中有访问 MainViewModel 属性的元素,所以我只想更改 Validation.Error 事件绑定(bind)的 DataContext ...如果可能的话...

谢谢。

最佳答案

Validation.Error是一个事件,而不是一个属性。您不能将绑定(bind)设置为事件。

您可以使用 MVVM Light 的 EventToCommand 之类的东西。 , 或者微软自己的Interactivity EventTrigger将命令与事件相关联。

但是在代码隐藏中添加一个常规事件处理程序并从那里调用一些 View 模型代码确实没有任何问题......与许多人似乎认为的相反,MVVM 并没有禁止使用代码隐藏和您所做的与 EventToCommand 或 EventTrigger 在幕后所做的并没有太大区别。

首先,只需为 Validation.Error 设置事件处理程序名称即可。事件。

<Grid Validation.Error="ValidationEvent" />

然后在你的代码隐藏中做任何你想做的事情。
private void ValidationEvent(object sender, ValidationErrorEventArgs e)
{
// Something useful

// Some call to VM code
(this.DataContext as MainViewModel).SomeMethod();
}

这与您的 DataContext 无关(当然,只要您将 this.DataContext 转换为正确的类型)。

事件处理程序不依赖于您的 DataContext,只有绑定(bind)。

关于WPF。更改事件绑定(bind)上的 DataContext 以访问 MVVM 项目的代码隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30894063/

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