【问题标题】:WPF mvvm View won't update when called from different ViewModel从不同的 ViewModel 调用 WPF mvvm View 时不会更新
【发布时间】:2021-04-29 16:15:19
【问题描述】:

我一直在尝试用自己的 VM 更新用户控件内的属性。

<Label Content="{Binding Path =LabelText ,UpdateSourceTrigger=PropertyChanged }" Grid.Column="0"/>

标签本身在我在 VM 的构造函数中设置它的文本时起作用,并且如果我在 VM 中使用命令也会更新。

但是从外部改变它不会做任何事情:

        private LabelTextBoxVM _testThing;
        public LabelTextBoxVM TestThing
        {
            get => _testThing;
            set
            {
                _testThing = value;
                NotifyPropertyChanged("TestThing");
            }
        }

           private void Update()
        {
            TestThing.LabelText = "Eureka";
            TestThing.TextBoxText = "Wooosh";
            NotifyPropertyChanged("TestThing");
        }

据我所知,为 TestThing 调用 NotifyPropertyChanged 应该会更新 Label 和 Textbox 的内容,但没有任何反应。

【问题讨论】:

  • 我认为你也需要为 LabelText 和 TextBoxtext 实现 notifypropertychanged
  • 问题是“具有自己的 VM 的用户控件”。 UserControl 不应该有自己的私有视图模型实例,该实例与应用程序的视图模型结构断开连接。相反,它应该通过从其父元素(例如它所在的窗口或页面)继承其 DataContext 属性的值来获取其视图模型(或更准确地说是其属性的绑定的源对象)。
  • @Clemens 你能告诉我如何实际实现类似的东西吗?因为我的解决方案是寻找指南的产物,显然我还是错了。
  • 不确定您到底需要什么。您不需要“实现”任何东西,只需使用框架的功能即可。也许看看如何在Control authoring overview 中声明依赖属性。另外需要注意的是,在标签的内容绑定中设置UpdateSourceTrigger=PropertyChanged 是没有意义的。它在 OneWay Binding 中无效,与 PropertyChanged 事件无关。

标签: c# wpf mvvm binding viewmodel


【解决方案1】:

@克莱门斯

我在另一个问题中找到了答案,实际上是你提供的:

wpf-mvvm-usercontrol-binding

我必须在父视图中设置我的 DataContext,绑定到父视图中的属性,并删除 childVM 中的 Datacontext

所以:

<myViewes:UserControlName DataContext="{Binding VMProperty}/>"

而且这部分不能在我的用户控件中:

<UserControl.DataContext>
        <viewModels:UserControlVM/>
</UserControl.DataContext>

我猜这就是你所说的“继承”虚拟机的意思

谢谢!

【讨论】:

    猜你喜欢
    • 2014-03-08
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多