[英]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并不是一个好习惯。 尝试通过以下方式进行操作:
问候,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.