从另一个视图mvvm刷新用户控件视图/数据绑定

时间:2014-03-18 11:56:15

标签: c# wpf mvvm binding

我有2个用户控件,代表MVVM模式中的两个视图。第二个控件的视图模型被声明为第一个用户控件的视图模型的childViewModel。

我想更新第二个控件视图的绑定,并在第一个控件收到数据时刷新/更新。

如果用户控件是一个单独的窗口(通过创建一个新实例并传递新的数据绑定值并使用ShowDialog()),我能够做到这一点,但我设想它们是一个单独的两个控件窗口我需要能够刷新/更新第二个视图。

如何更新第二个视图?

1 个答案:

答案 0 :(得分:0)

这可以帮到你:

public class VM1 : DependencyObject
{
    public VM1()
    {
        //as you see the Child is instantiated when VM1 is instantiated
        Child = new VM2();
    }
    public VM2 Child
    {
        get { return (VM2)GetValue(ChildVmProperty); }
        set { SetValue(ChildVmProperty, value); }
    }
    public static readonly DependencyProperty ChildVmProperty =
        DependencyProperty.Register("Child", typeof(VM2), typeof(VM1), new UIPropertyMetadata(null));
    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(VM1), new UIPropertyMetadata(null));
}
public class VM2 : DependencyObject
{
    public string InnerText
    {
        get { return (string)GetValue(InnerTextProperty); }
        set { SetValue(InnerTextProperty, value); }
    }
    public static readonly DependencyProperty InnerTextProperty =
        DependencyProperty.Register("InnerText", typeof(string), typeof(VM2), new UIPropertyMetadata(null));
}
在window.xaml中

<DockPanel>
    <my:Control1 DataContext="{Binding}"/>
    <my:Control2 DataContext="{Binding Child}"/>
</DockPanel>

但请确保在window.xaml.cs中正确设置DataContext:

public MainWindow()
{
    InitializeComponent();
    this.DataContext = new VM1();
}

现在在每个控件绑定到属性名称:

Control1.xaml:

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

Control2.xaml:

<Grid>
    <TextBox Text="{Binding InnerText}"/>
</Grid>
相关问题