绑定对继承属性不起作用
本文关键字:不起作用 属性 继承 绑定 | 更新日期: 2023-09-27 18:17:03
在ComboBox中使用绑定有一个问题。
<ComboBox
Margin="2"
x:Name="itemSelector"
SelectionChanged="itemSelector_SelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Id}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
我的对象是public class MyButton : MyElement
, Id属性在MyElement类中设置。
当然Id是一个公共属性:public string Id;
。当我尝试访问MyButton类中的属性时,它可以工作,但对于"Id"字段,我什么也得不到。
你不能绑定到一个字段;你需要把Id
变成一个属性。
将字段替换为public string Id { get; set; }
应该是属性(带有getter和setter),而不是字段。因为您应该通知UI属性的值发生了变化(并且您应该实现INotifyPropertyChanged接口)
代码应该看起来像c# 5public string Id
{
get { return _id; }
set { SetProperty(ref _id, value); }
}
private string _id;
或c# 4
public string Id
{
get { return _id; }
set
{
_id = value;
RaisePropertyChanged(() => Id);
}
}
private DateTime _id;
完整的代码你可以在这篇博文中看到(c#语言的4和5版本)http://jesseliberty.com/2012/06/28/c-5making-inotifypropertychanged-easier/
注意c# 5需要。net 4.5,因此你的应用程序不能在WinXP上运行。c# 4需要。net 4.0,所以没有这个限制。