2011-06-08 150 views
0

我需要添加什么来设置我ViewModel实例上的公共属性?我想在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的setter方法不会被调用。必须有一些基本的MVVM事情我做错了。

+0

这与MVVM无关。你做错了什么。这实际上会工作,我已经做了好几次。 – Will 2011-06-09 14:10:03

+1

好的谢谢。我得到它的工作。我的问题是viewmodels的构造函数在设置值之前调用,而我的代码并不期待这个。 – vanslyker 2011-06-09 15:22:03

+0

我建议你添加最后一条命令作为答案,并将其标记为已接受。 ;)这将使解决方案更加可见。 – 2011-06-09 17:16:22

回答

0

我上面的psuedo代码实际工作。我有我的ViewModel的构造函数的另一个问题,让我难住。

0

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

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

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

+0

我不希望用户能够更改MyProperty,也不应该在页面上可见。我在多个视图中使用相同的ViewModel,每个视图对MyProperty都有不同的值。 – vanslyker 2011-06-09 14:46:22

0
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> 

这里我设置好的属性为静态字符串,但你可以回顾你的任何View的控制,并使用它的值将其推送到ViewModel中。

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