【问题标题】:Set property on ViewModel from View从 View 设置 ViewModel 的属性
【发布时间】:2011-06-08 23:02:28
【问题描述】:

我需要添加什么才能从我的视图中为我的 ViewModel 实例设置公共属性?我想在 ViewModel 资源上设置一些属性,而不是从视图中的某个元素绑定它。

查看 XAML:

<UserControl.Resources>
   <vm:MainViewModel x:Key="mainViewModel" MyProperty="30" />
</UserControl.Resources>
<UserControl.DataContext>
   <Binding Source={StaticResource mainViewModel}" />
</UserControl.DataContext>

MainViewModel.cs(实现 INotifyPropertyChanged)

private int _myProperty;
public int MyProperty{
    get { return _myProperty; }
    set 
    { 
        _myProperty = value;
        OnPropertyChanged("MyProperty");
    }
}

永远不会调用 MyProperty 上的设置器。一定有一些基本的 MVVM 事情我做错了。

【问题讨论】:

  • 这与 MVVM 无关。你做错了其他事情。这实际上会起作用,我已经做了好几次了。
  • 好的,谢谢。我让它工作了。我的问题是在设置值之前调用了视图模型的构造函数,而我的代码没有预料到这一点。
  • 我建议您将最后一个命令添加为答案,并将其标记为已接受。 ;) 这将使解决方案更加明显。

标签: silverlight mvvm


【解决方案1】:

通常您会创建一个绑定,将 ViewModel 上的属性与控件的属性绑定。例如,您可以像这样将 MyProperty 绑定到文本框:

<TextBox Text="{Binding MyProperty}" />

由于 UserControl.DataContext 指定的父数据上下文是 MainViewModel 的一个实例,因此此绑定将绑定到该对象的属性。

【讨论】:

  • 我不希望用户能够更改 MyProperty,也不希望它在页面上可见。我在多个视图中使用相同的 ViewModel,每个视图都有不同的 MyProperty 值。
【解决方案2】:
    Well what you can do is set the MouseDown of a control such as a 'save' button on a method of the code-behind of your view. Then in the codebehind, you set your ViewModel's property or call his method.

在你的 View.xaml.cs 中你需要这样的东西

    private MyViewModele myVM;

    public MyView()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(Initialized);  //After loading, call Initialized(...)
    }

    private void Initialized(object sender, RoutedEventArgs e)
    {
        myVM= this.DataContext as MyViewModele ; //Reference to your ViewModel
    }

    private void Label_General(object sender, RoutedEventArgs e)
    {
       myVM.Property = "w/e"; //Set the ViewModel property
    }

在您的 View.xaml 中

<Label 
        Content="Click this label"
        MouseDown="Label_General"
        >
</Label>

这里我将 Property 设置为静态字符串,但您可以检索 View 的任何控件并使用其值将其推送到 ViewModel 中。

我希望这能回答你的问题。

【讨论】:

    【解决方案3】:

    我上面的伪代码确实有效。我的 ViewModel 的构造函数遇到了另一个问题,这让我很困惑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 2010-11-03
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多