【问题标题】:Changing values of DataContext in Command in WPF在 WPF 中的 Command 中更改 DataContext 的值
【发布时间】:2020-06-20 11:50:58
【问题描述】:

我想更改ViewModel 属性的值(与DataContext 绑定)。使用经典事件非常容易,使用命令它成为艰巨的任务。这是我的代码:

公共部分类 MainWindow : Window
    {
        ViewModel _vm = new ViewModel();
        公共主窗口()
        {
            初始化组件();

            _vm.BtnClick = new BtnClick();

            数据上下文 = _vm;
        }
    }

公共类 BtnClick : ICommand
    {
        公共事件 EventHandler CanExecuteChanged
        {
            添加 { CommandManager.RequerySuggested += 值; }
            删除 { CommandManager.RequerySuggested -= 值; }
        }

        public bool CanExecute(对象参数)
        {
            返回真;
        }

        公共无效执行(对象参数)
        {
            Debug.WriteLine(parameter.ToString());
        }
    }

公共类视图模型
    {
        公共 ICommand BtnClick { 获取;放; }
        公共字符串输入{获取;放; }
        公共字符串输出{获取;放; }
    }
<StackPanel>
        <TextBox Text="{Binding Input}"></TextBox>
        <TextBlock Text="{Binding Output}"></TextBlock>
        <Button Command="{Binding Path=BtnClick}" CommandParameter="{Binding Input}">Translate</Button>
    </StackPanel>

命令正确地从TextBox 获取值,现在我想用这个值做一些事情并将它保存到Output。问题是从命令的角度来看,我无法同时访问 DataContextViewModel

【问题讨论】:

  • 是什么让您认为您需要访问 DataContext?您要解决的问题是什么? Command 实例实际上应该在您的 ViewModel 中定义,而不是在 View 中。
  • 为了更改TextBlock Text,我必须访问ViewModel。没有其他办法。
  • MVVM 的全部意义在于您通过 ViewModel 属性进行所有更新,并且相应的 UI 控件将通过数据绑定进行更新。不过,这确实需要您的 ViewModel 实现 INotifyPropertyChanged

标签: c# wpf command


【解决方案1】:

任何命令的实现通常都在视图模型中。

经常使用框架或帮助类。

例如:

https://riptutorial.com/mvvm-light/example/32335/relaycommand

公共类 MyViewModel { .....

public ICommand MyCommand => new RelayCommand(
   () =>
  {
    //execute action
    Message = "clicked Button";
  },
  () =>
  {
    //return true if button should be enabled or not
    return true;
  }

);

这里有一个带有“点击按钮”的匿名方法。

这将捕获父视图模型中的变量。

因此,您可以在视图模型中设置一个公共属性,该属性绑定到视图中的文本属性。

为了让视图响应,您需要在该公共属性的设置器中实现 inotifypropertychanged 并引发属性更改。

https://docs.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-property-change-notification.

从上面。

如果 PersonName 绑定到视图中的文本块。

  public string PersonName
  {
      get { return name; }
      set
      {
          name = value;
          // Call OnPropertyChanged whenever the property is updated
          OnPropertyChanged();
      }
  }

在命令中你可以这样做:

 PersonName = "Andy";

调用 PersonName 的 setter,绑定到 PersonName 的文本块将读取新值。

【讨论】:

猜你喜欢
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多