繁体   English   中英

C# 用户控件 (MVVM) 显示 MV 中的属性

[英]C# User Control (MVVM) surface a property in MV

我觉得我可能在这里遗漏了一些东西,或者它不可行(我很难相信)。

我有一个使用 MVVM 架构的 UserControl。

UserControl 看起来像这样。

 public partial class UserControl1 : UserControl
    {
        private string _labelContents;

        public UserControl1()
        {
            InitializeComponent();
            DataContext = new UserControl1_VM();
        }
    }

虚拟机看起来像这样。

公共类UserControl1_VM:INotifyPropertyChanged {私有字符串_labelContents =“从VM设置”;

    public string LabelContent
    {
        get => _labelContents;
        set { _labelContents = value; OnPropertyChanged("LabelContent"); }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

我希望能够放入 MainView 或类似的:

  <mv:UserControl1 LabelContent="My Text"></mv:UserControl1>

但是 VS 声明它“无法解析符号 LabelContent”。 这是可以理解的,因为它在视图模型中。 如果不将该属性放入 UserControl 后面的代码中,并通过它传递值似乎是不可能的。 我可能只是在寻找错误的东西。

这是一个非常基本的例子,但我认为 LabelContent 需要是一个依赖属性,因为它本身即最终绑定到它。

<mv:UserControl1 LabelContent="{Binding LabelText}"></mv:UserControl1>

对此有任何帮助都会很棒,因为它让我挠头,让我秃顶!!

只是为了让您知道它是否不是依赖属性,但它看起来很笨拙。

干杯

詹姆士

您不需要 UserControl 的任何视图模型,只需要一个依赖属性:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public string LabelContent
    {
        get { return (string)GetValue(LabelContentProperty); }
        set { SetValue(LabelContentProperty, value); }
    }

    public static readonly DependencyProperty LabelContentProperty = DependencyProperty.Register
    (
        nameof(LabelContent),
        typeof(string),
        typeof(UserControl1),
        new PropertyMetadata(String.Empty)
    );    
}

然后将其放在视图中并分配或绑定属性:

<mv:UserControl1 Name="uc1" LabelContent="My Text"/>

<mv:UserControl1 Name="uc2" LabelContent="{Binding Path=LabelContent, ElementName=uc1}"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM