繁体   English   中英

将类属性绑定到MVVM中的UserControl

[英]Binding class properties to UserControl in MVVM

我有一个包含名为Text的字符串属性的类。

   public class Time
    {
        private string _text;
        public string Text
        {
            get { return _text; } 
            set { _text = value; }
        }
    }

我也有一个包含此类的自定义UserControl。

public partial class MyUserControl : UserControl, INotifyPropertyChanged
{
<...>
    private Time _myTime;
    public Time MyTime
    {
            get { return _myTime; }
            set { _myTime= value; NotifyPropertyChanged(); } 
    }
}

我想从ViewModel中创建上面的UserControl,并为其分配一个Time类及其所有属性:

void SomeMethod()
{
    Time TestTime = new Time();
    TestTime.Text = "Hello world";

    MyUserControl control = new MyUserControl();
    control.MyTime = TestTime;

    controlViewer = new System.Collections.ObjectModel.ObservableCollection<Control>();
    controlViewer.Add(control);
        // on my main window, I have an ItemsControl with 
        // ItemsSource="{Binding controlViewer}".
}

UserControl的XAML包含以下文本框:

<TextBox Text="{Binding MyTime.Text}"/>

然后,我可以以编程方式调用control.MyTime.Text属性并获得“ Hello world”值,但是它无法显示在新创建的MyUserControl的文本框中。

您必须将绑定的源对象设置为UserControl实例,例如,通过如下设置绑定的RelativeSource属性:

<TextBox Text="{Binding MyTime.Text,
                RelativeSource={RelativeSource AncestorType=UserControl}}"/>

除此之外,在view元素中实现INotifyPropertyChanged接口并不常见。 您可以改为将MyTime声明为依赖项属性:

public static readonly DependencyProperty MyTimeProperty =
    DependencyProperty.Register("MyTime", typeof(Time), typeof(MyControl));

public Time MyTime
{
    get { return (Time)GetValue(MyTimeProperty); }
    set { SetValue(MyTimeProperty, value); }
}

在ViewModel中创建UserControl并不是一个好习惯。 尝试通过以下方式进行操作:

  1. 使用ItemsControl创建XAML主窗口(最好使用ListView / ListBox,因为它们允许选择)。
  2. 使用Time类对象的ObservableCollection创建ViewModel,然后将此ViewModel绑定到MainWindow作为视图模型。
  3. 使用要在集合中查看的对象初始化ViewModel。
  4. 使用UserControl为每个ItemsControl集合成员定义DataTemplate。

问候,

暂无
暂无

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

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