如何在MVVM Caliburn.Micro中绑定用户控件?

时间:2018-01-11 12:40:55

标签: c# wpf mvvm caliburn.micro

我有用户控件(下一个UC)标签。我需要在按钮上点击更改UC标签内容。在UC代码隐藏中,我创建 DependencyProperty 以及更改标签的方法。

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上,我获得了控件和按钮的绑定。

<c:UserControl1 InfoLabel="{Binding InfoLabel1}" />
<Button  x:Name="ChangeUserControllButton"/>

在ShellViewModel上我有绑定 InfoLabel1

private string infoLabel= "something";

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

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

问题是当 UC 初始化时,它就会起作用。我的意思是来自UC的标签会有内容&#34;&#34; ,但是当我点击按钮时,内容不会更改为&#34; Hello world&#34 ;。怎么做对了?

1 个答案:

答案 0 :(得分:2)

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

参考Caliburn.Micro.PropertyChangedBase

更新ShellViewModel以从PropertyChangedBase派生,然后在属性调用中使用一种可用的方法,以允许您的视图模型通知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/阅读更多内容,了解如何使用该框架。