在WPF窗口上关闭事件触发器 - DataContext的问题

35 浏览
0 Comments

在WPF窗口上关闭事件触发器 - DataContext的问题

我有一个视图,在窗口资源中初始化了一个视图模型。此外,我给我的网格设置了DataContext。

我的问题是,如何在保持mvvm在内存中的情况下,将一个命令添加到我的窗口关闭事件中?我尝试了这个帖子的版本:Handling the window closing event with WPF / MVVM Light Toolkit,但是使用事件触发器是不起作用的,因为我无法从我的网格外部访问视图模型,所以无法访问我的命令。

有解决方案吗?

问候

Jannik

编辑:这是我的xaml:


    
        
    
    ...

0
0 Comments

问题的原因是在WPF窗口上的Closing事件触发器中,无法正确访问到DataContext。解决方法是通过在窗口的构造函数中设置MainViewModel作为DataContext,并在MainViewModel的构造函数中创建其他ViewModel的实例。

解决方法的具体实现是,首先在XAML中将窗口的DataContext设置为MainViewModel的实例。然后,在窗口的构造函数中使用this.DataContext = new MainViewModel();来设置DataContext。接着,在MainViewModel的构造函数中使用this.MyGridViewModel = new OtherViewModel();来创建OtherViewModel的实例。

通过这种方式,我们可以通过各个ViewModel之间的引用来找到所需的对象,从而解决了无法正确访问DataContext的问题。

0
0 Comments

问题的出现原因:

该问题是由于在WPF窗口的Closing事件上使用了触发器,并尝试使用静态资源的DataContext导致的。在代码中,触发器指定了一个命令,该命令绑定到了一个静态资源的CloseCommand属性。

解决方法:

要解决这个问题,可以通过在XAML中的Grid元素上设置DataContext来显式指定ViewModel。在代码中,可以将MainWindowViewModel的构造函数中的LastInstance字段更改为自定义的数据存储方法。此外,还需要实现一个自定义的Command类来替代使用的Command接口。

完整解决方案如下:


    
        
    
    
        
            
        
    
    
        
    

public MainWindowViewModel()
{
    //save or load here...
    if (LastInstance != null) Txt = LastInstance.Txt;
    CloseCommand = new Command(o => LastInstance = this);
    //...
}
public static ViewModel LastInstance;
//Txt Dependency Property
public string Txt
{
    get { return (string)GetValue(TxtProperty); }
    set { SetValue(TxtProperty, value); }
}
public static readonly DependencyProperty TxtProperty =
    DependencyProperty.Register("Txt", typeof(string), typeof(ViewModel), new UIPropertyMetadata(null));
//CloseCommand Dependency Property
public Command CloseCommand
{
    get { return (Command)GetValue(CloseCommandProperty); }
    set { SetValue(CloseCommandProperty, value); }
}
public static readonly DependencyProperty CloseCommandProperty =
    DependencyProperty.Register("CloseCommand", typeof(Command), typeof(ViewModel), new UIPropertyMetadata(null));

感谢提问者指出了使用Source来设置DataContext的方法,以前我并不知道这个!

说实话,我之前也不知道! 🙂

0