我有一个MainWindow,其DataContext设置为MainWindowViewModel.cs类。 在MainWindow内部,我有2个用户控件,每个用户控件都绑定到相应的ViewModel(例如UserControl1ViewModel.cs和UserControl2ViewModel.cs)。
如何从MainWindowViewModel.cs获取对用户控件ViewModel的引用,以便我可以操作他们的数据?
答案 0 :(得分:2)
一种基本方法如下
在实例化父级的DataContext时,实例化子用户控件的DataContext 示例
<StackPanel>
<TextBox Text="{Binding Text}"/>
<uc:UC1 DataContext="{Binding Uc1Vm}"/>
<uc:UC2 DataContext="{Binding Uc2Vm}"/>
</StackPanel>
以下是主视图模型
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel()
{
//Below would be replaced by an IOC container instatiation in real world(Unity, MEF etc..)
Uc1Vm = new UC1ViewModel(),
Uc2Vm = new UC2ViewModel()
};
}
}
MainWindowViewModel可以由2个子视图模型组成,如下所示
public UC1ViewModel Uc1Vm { get; set; }
public UC2ViewModel Uc2Vm { get; set; }
您可以如下所示操作子控件,例如从MainWindowViewModel
/// <summary>
/// Text is in MainWindowViewModel
/// </summary>
public string Text
{
get { return _text;}
set
{
if(value !=_text)
{
_text = value;
//User control1 has Text property in its view model
Uc1Vm.Text = _text;
//User control2 has Content property in its view model
Uc2Vm.Content = _text;
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Text"));
}
}
}
}
如果这有帮助或您有任何疑问,请告诉我。