【问题标题】:How to binding User Control in MVVM Caliburn.Micro?如何在 MVVM Caliburn.Micro 中绑定用户控件?
【发布时间】:2018-01-11 12:40:55
【问题描述】:

我有一个带有 标签用户控件(下一个 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 的 label 会有内容 "something",但是当我点击按钮时,内容不会变为“Hello world”。怎么弄好?

【问题讨论】:

    标签: c# wpf mvvm caliburn.micro


    【解决方案1】:

    视图模型需要实现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/ 上阅读更多内容以获取有关如何使用该框架的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2020-08-10
      • 2016-05-01
      • 2011-04-07
      • 2010-12-15
      • 2011-09-08
      相关资源
      最近更新 更多