MainWindowViewModel引用到用户控制ViewModel实例



我有一个MainWindow与DataContext设置为其MainWindowViewModel.cs类。在MainWindow中,我有2个用户控件,每个用户控件都绑定到它相应的ViewModel(例如UserControl1ViewModel.cs和UserControl2ViewModel.cs)。

我如何从MainWindowViewModel.cs中获得对用户控制视图模型的引用,以便我可以操纵他们的数据?

一个基本的方法如下

在实例化父用户控件的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"));
                }
            }
        }
    }

如果这对你有帮助或者你有任何疑问请告诉我。

最新更新