【发布时间】:2017-12-21 13:01:40
【问题描述】:
在我的视图模型中:
public string MyProperty{ get; set; }
public MyViewModel()
{
MyProperty = "hello";
}
我已经定义了一个字符串属性。
现在,我想从我的页面绑定到这个属性:
Text="{Binding MyProperty}"
但这不起作用 - 没有显示任何文字。我错过了什么?
编辑: 我的视图模型继承自:
public class Observable : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
编辑 2:
我已经修改了我的视图模型:
private string _myProperty;
public string MyProperty
{
get => _myProperty;
set => Set(ref _myProperty, value);
}
public MyViewModel()
{
_myProperty = "hello";
}
和 xaml:
Text="{Binding MyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
但它仍然无法正常工作。
编辑3:我认为问题在于Text属性是自定义控件的注册依赖属性:
public sealed partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
DataContext = this;
}
public string Text
{
get => (string)GetValue(s_textProperty);
set => SetValue(s_textProperty, value);
}
public static readonly DependencyProperty s_textProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyControl), new PropertyMetadata(null));
}
在控件的 xaml 中我有:
<TextBlock Text="{Binding Text}" />
这个:
<MyControl Text="{Binding MyProperty}"/>
在我使用自定义控件的页面中。
【问题讨论】:
-
您是否在视图上设置了数据上下文? var view = new MyView(); var viewModel = new MyViewModel(); view.DataContext = viewModel;
-
@JanWidmer 我有。
-
要绑定标签的文字吗?
-
在属性的getter和setter中放一个调试点?
-
您是否在输出窗口中遇到任何绑定错误?