如何访问WPF MVVM的视图模型中代码背后的属性?

问题描述 投票:0回答:2

我目前正在使用WPF MVVM模式实现应用程序。我遇到了一个问题,我需要在mediator方法的codebehind(假设Author.xaml.cs)中分配一些属性(IsClickedYes为true),然后当mediator返回到特定的视图模型(AuthorViewModel.cs)时,从AuthhorViewModel.cs访问Author.xaml.cs中的IsClickedYes属性。我该如何实现?

Author.cs

public class Author
{
    private bool _isClickedYes;

    public bool IsClickedYes
    {
     get { return _isClickedYes; }
     set { _isClickedYes= value; }
    }
    public Author()
    {
    Mediator.Register("SetClickedYesProperty",SetClickedYes);
    }

    private void SetClickedYes(object parameter)
    {
     //Show a Confirm Message Dialog here then if user clicked yes set IsClickedYes property to true

    _isClickedYes=true;
    }
}

AuthorViewModel.cs

public class AuthorViewModel
{
//this will call the SetClickedYes method in Author.xaml.cs
Mediator.NotifyCollegue("SetClickedYesProperty",null);

//then here I need to access the IsClickedYes Property value of Author.xaml.cs 
if IsClickedYes == true , then do a certain operation otherwise do nothing.


}

如果我尝试在AuthorViwModel中创建属性并在代码隐藏中设置该属性,则当它从调解器返回时,该属性将为null。因此,这就是为什么我在代码隐藏中创建属性并在其中分配值,然后尝试从View Model访问它的原因。我如何才能实现这一目标,还有其他方法可以实现吗?如果还有其他更好的方法可以实现这一目标,请有人指导我吗?任何建议将不胜感激!

c# wpf mvvm mediator
2个回答
0
投票
关于视图触发视图模型操作时,您应该想到命令模式。

但是,如果IsClicked反映了视图模型状态,例如IsDataFilterEnabled,则可以按照其他人的建议使用数据绑定。但是在这种情况下,您为Author属性选择了一个非常不好的名字。名称

IsClicked和按钮的状态是关联的。

Author.xaml.cs

public partial class Author : Window { private bool _isClicked; public bool IsClicked { get { return _isClicked; } set { _isClickedYes= value; } } public Author() { Mediator.Register("EnableIsClickedProperty", EnableIsClicked); } private void EnableIsClicked(object parameter) { _isClicked = dialogResult; // Assuming that AuthorViewModel is the DataContext of the Author view var viewModel = this.DataContext as AuthorViewModel; if (_isClicked && viewModel.DoCertainOperationCommand.CanExecute()) { viewModel.DoCertainOperationCommand.Execute(); } } }

AuthorViewModel.cs

public class AuthorViewModel { public ICommand DoCertainOperationCommand => new RelayCommand(DoCertainOperation, CanExecuteDoCertainOperation); private void DoSomething() { //this will call the EnableIsClicked method in Author.xaml.cs Mediator.NotifyCollegue("EnableIsClickedProperty", null); } private void DoCertainOperation(object param) { // As this method is only invoked by the view when Author.IsClicked == true, // the view model doesn't need to care about the view's property states. // IsClicked is UI logic and belongs solely to the view. } private bool CanExecuteDoCertainOperation => true; } 为简洁起见,我没有在此处发布RelayCommand的代码。您或者已经拥有自己的实现,或者在web中可以找到几十个。

或者直接(从后面的代码中)调用视图模型的API。
© www.soinside.com 2019 - 2024. All rights reserved.