在我的视图模型中:
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}"/>
在我使用自定义控件的页面中。
你的类应该实现INotifyPropertyChanged
并拥有这样的属性访问器:
public event PropertyChangedEventHandler PropertyChanged;
private string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
OnPropertyChanged();
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
在 XAML 中:
Text="{Binding MyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
评论:
Mode = TwoWay - 如果被任一更改,属性将在 UI 和代码中更改。UpdateSourceTrigger - 对 PropertyChanged 事件做出反应。另外,请阅读 DataContext :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句