Silverlight 从视图设置ViewModel的属性
要从视图中设置ViewModel实例的公共属性,需要添加什么?我想在ViewModel资源上设置一些属性,而不是从视图中的某个元素绑定它 查看XAML:Silverlight 从视图设置ViewModel的属性,silverlight,mvvm,Silverlight,Mvvm,要从视图中设置ViewModel实例的公共属性,需要添加什么?我想在ViewModel资源上设置一些属性,而不是从视图中的某个元素绑定它 查看XAML: <UserControl.Resources> <vm:MainViewModel x:Key="mainViewModel" MyProperty="30" /> </UserControl.Resources> <UserControl.DataContext> <Bindi
<UserControl.Resources>
<vm:MainViewModel x:Key="mainViewModel" MyProperty="30" />
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source={StaticResource mainViewModel}" />
</UserControl.DataContext>
从未调用MyProperty上的setter。我一定是做错了一些基本的MVVM操作。通常,您会创建一个绑定,将ViewModel上的属性与控件的属性绑定在一起。例如,您可以将MyProperty绑定到文本框,如下所示:
<TextBox Text="{Binding MyProperty}" />
由于UserControl.DataContext指定的父数据上下文是MainViewModel的实例,因此此绑定将绑定到该对象的属性
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.
在your 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
}
在your View.xaml中
<Label
Content="Click this label"
MouseDown="Label_General"
>
</Label>
在这里,我将属性设置为静态字符串,但您可以检索视图的任何控件,并使用其值将其推送到ViewModel中
我希望这能回答你的问题。我上面的psuedo代码实际上可以工作。我的ViewModel的构造函数还有一个问题,这让我很困惑。这与MVVM无关。你做错了别的事。这实际上会起作用的,我已经做了好几次了。好的,谢谢。我让它工作了。我的问题是,在设置值之前调用了viewmodels的构造函数,我的代码没有预料到这一点。我建议您添加上一个命令作为答案,并将其标记为已接受。;)这将使解决方案更加可见。我不希望用户能够更改MyProperty,也不希望它在页面上可见。我在多个视图中使用相同的ViewModel,每个视图的MyProperty值都不同。
<Label
Content="Click this label"
MouseDown="Label_General"
>
</Label>