簡體   English   中英

從另一個視圖mvvm刷新用戶控件視圖/數據綁定

[英]Refresh user control view/data binding from another view mvvm

我有2個用戶控件,分別代表MVVM模式中的兩個視圖。 第二個控件的視圖模型被聲明為第一個用戶控件的視圖模型的childViewModel。

我想更新第二個控件視圖的綁定,並在第一個控件收到其數據時刷新/更新它。

如果用戶控件是一個單獨的窗口(通過創建一個新實例並傳遞新的數據綁定值並使用ShowDialog() ),則能夠執行此操作,但是由於我將它們設想為一個窗口中的兩個控件,因此我需要能夠刷新/更新第二個視圖。

如何更新第二個視圖?

這可以幫助您:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM