【问题标题】:Update multiple usercontrols with binding使用绑定更新多个用户控件
【发布时间】:2012-12-04 17:21:04
【问题描述】:

我已尝试搜索,但找不到答案。我有一个包含两个用户控件 A 和 B 的主窗口。它们都有单独的 ViewModel,但从同一个模型实例中获取数据。当我更改用户控件 A 中的属性时,我希望它更新用户控件 B 中的相应值。

似乎OnPropertyChanged("MyProperty") 仅更新同一 ViewModel 中的属性。我知道 ViewModel B 背后的数据与 ViewModel A 相同,因为我可以使用刷新按钮手动刷新数据。

有没有什么简单的方法可以刷新其他用户控件中的值?

【问题讨论】:

  • 这是一个你必须同时同步两个源的场景:你可能需要truss.codeplex.com
  • 但是来源是一样的。有没有办法让 PropertyChanged 成为应用程序范围而不是 ViewModel 范围?

标签: c# wpf mvvm binding user-controls


【解决方案1】:

如果您需要这种行为,模型还必须实现INotifyPropertyChanged 接口。

class Model : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string someText = string.Empty;
    public string SomeText
    {
        get { return this.someText; }
        set { this.someText = value; this.PropertyChanged(this, new PropertyChangedEventArgs("SomeText")); }
    }
}


class ViewModelA : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Model data;
    public Model Data
    {
        get { return this.data; }
        set { this.data = value; this.PropertyChanged(this, new PropertyChangedEventArgs("Data")); }
    }
}

class ViewModelB : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Model data;
    public Model Data
    {
        get { return this.data; }
        set { this.data = value; this.PropertyChanged(this, new PropertyChangedEventArgs("Data")); }
    }
}

您必须将相同的模型实例传递给两个视图模型,然后像这样在您的控件中绑定数据。

对于使用 ViewModelA 作为 DataContext 的 TextBoxA

<TextBox x:Name="TextBoxA" Text="{Binding Path=Data.SomeText}" />

对于使用 ViewModelB 作为 DataContext 的 TextBoxB

<TextBox x:Name="TexTBoxB" Text="{Binding Path=Data.SomeText}" />

现在,当您更改其中一个文本框中的文本时,另一个文本框中的文本会自动更改。

【讨论】:

  • 这正是我尝试过的。 INotifyPropertChanged 在所有类中实现。我可以强制它使用刷新按钮进行更新,并获得所需的结果。所以我知道他们使用该对象的相同实例。看来必须在 ViewModelB 中调用 OnPropertyChanged 才能更新 View B 中的控件。
  • 我现在再次对其进行了测试,这绝对有效。也许看起来,它只适用于单击刷新按钮,因为您的 TextBox 会失去焦点?一般绑定仅在文本框失去焦点时更新。所以尝试将绑定设置为:Text="{Binding Path=Data.SomeText, UpdateSourceTrigger=PropertyChanged}"。也许这会有所帮助。
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多