我有一些UserControl,它DataContext绑定到ViewModel,如何设置ViewModel的属性XAML?是否可以?
UPD:抱歉不太清楚,我试图得到这样的结果:UserControl 的 DataContext 绑定到 ViewModel,我需要将 ViewModel 的属性设置为某些内容(比方说,UserControl 的 Width 属性)。是否可以?
UPD2:这似乎是不可能的。我知道 TwoWay 绑定模式等,我想做的事情 - 将 ViewModel 的属性设置为 UserControl 的属性
这个例子应该很清楚了
<Set Property={Binding SomePropertyOnViewModel}
Value={Binding RelativeSource={RelativeSource Self},
Path=SomePropertyOnUserControl}>
Run Code Online (Sandbox Code Playgroud)
我不确定我是否准确理解了这个问题。
但这里有一个例子。它会:
通过在 xaml 中ExampleViewModel设置用户控件属性来创建用户控件内部类型的视图模型DataContext
在 xaml 中创建一个文本框并将其绑定到视图模型
TextInViewModel字符串属性。
设置常用INotifyPropertyChanged接口(这个被提取到基类中ViewModelBase)
在 xaml 中创建视图模型并为其设置用户控件数据上下文:
<UserControl x:Class="MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test"
xmlns:viewModel="clr-namespace:ViewModels">
<UserControl.DataContext>
<viewModel:ExampleViewModel/>
</UserControl.DataContext>
<StackPanel Orientation="Horizontal" >
<Label>Enter Text here: </Label>
<TextBox Text="{Binding TextInViewModel}"></TextBox>
</StackPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
视图模型:
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
public class ExampleViewModel : ViewModelBase
{
/// <summary>
/// Property bound to textbox in xaml.
/// </summary>
public String TextInViewModel
{
get { return _textInViewModel; }
set
{
_textInViewModel= value;
RaisePropertyChanged("TextInViewModel");
}
}
private string _textInViewModel;
/// <summary>
/// Constructor.
/// </summary>
public ExampleViewModel()
{
}
}
Run Code Online (Sandbox Code Playgroud)
ill*_*ant -2
“如何从 XAML 设置 ViewModel 的属性?可能吗?”
所以,这似乎是不可能的,最多你可以完成 - 双向绑定,不幸的是,这不是我想要的。总而言之,这是一个相当糟糕的设计而不是一个问题