c# - 如何在 MVVM Caliburn.Micro 中绑定(bind)用户控件?

标签 c# wpf mvvm caliburn.micro

我有一个 用户控制 (下一个 UC)与 标签 .我需要 按钮 单击更改 UC 标签内容。在 UC 代码隐藏上,我创建了 依赖属性 以及更改 的方法标签 .

public string InfoLabel
    {
        get
        {
            return (string)this.GetValue(InfoLabelProperty);
        }
        set
        {
            this.SetValue(InfoLabelProperty, value);
        }
    }

    private static void InfoLabelChangeCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        UserControl1 uc = d as UserControl1;

        uc.CInfoLabel.Content = uc.InfoLabel;
    }

    public static readonly DependencyProperty InfoLabelProperty = DependencyProperty.Register("InfoLabel", typeof(string), typeof(UserControl1), new PropertyMetadata("", new PropertyChangedCallback(InfoLabelChangeCallback)));

在 ShellView 我得到了控件和按钮的绑定(bind)。
<c:UserControl1 InfoLabel="{Binding InfoLabel1}" />
<Button  x:Name="ChangeUserControllButton"/>

在 ShellViewModel 我有绑定(bind) 信息标签1 .
private string infoLabel= "something";

    public string InfoLabel1
    {
        get
        {
            return infoLabel;
        }
        set
        {
            infoLabel = value;
        }
    }

    public void ChangeUserControllButton()
    {
        InfoLabel1 = "Hello world";
    }

问题是当一个 加州大学 是初始化,然后它的工作。我的意思是 标签 来自 UC 将有内容 “某事” ,但是当我单击按钮时,内容不会更改为“Hello world”。如何使它正确?

最佳答案

View 模型需要实现INotifyPropertyChanged以便能够通知 UI 它应该刷新/更新,因为绑定(bind)模型已更改。我相信已经有一个提供该功能的基类。

引用 Caliburn.Micro.PropertyChangedBase

更新 ShellViewModel源自PropertyChangedBase然后在属性中调用允许您的 View 模型通知 UI 属性更改的可用方法之一。

public class ShellViewModel : PropertyChangedBase {

    private string infoLabel= "something";
    public string InfoLabel1 {
        get {
            return infoLabel;
        }
        set {
            infoLabel = value;
            NotifyOfPropertyChange();
            //Or
            //Set(ref infoLabel, value);
        }
    }

    public void ChangeUserControllButton() {
        InfoLabel1 = "Hello world";
    }

}

阅读更多 https://caliburnmicro.com/获取有关如何使用该框架的示例。

关于c# - 如何在 MVVM Caliburn.Micro 中绑定(bind)用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48207343/

相关文章:

c# - 如何测试自动命名状态机?

c# - Log4net 输出到我的文档

c# - ASP.NET 和 C# 之间有什么区别?

c# - WPF:双向绑定(bind)始终更新 - 单向绑定(bind)仅更新一次

C# WPF 应用程序在 VS 调试中运行,但不作为 EXE 运行

wpf - 将 DataGrid 行中的 DoubleClick 命令绑定(bind)到 VM

c# - 如何去除 ListBoxItem 周围的小填充?

wpf - 确定窗口在 WPF 中是否实际可见的最佳方法是什么

c# - Dragablz TabablzControl可见性属性不起作用

c# - 使用组合框 MVVM 绑定(bind)枚举描述