我已经阅读了有关数据绑定的在线文档,但仍无法使其正常工作。我只想了解数据绑定并按照应有的方式做事。
这是我的UI.xaml.cs中的代码
namespace mynamespace
{
class Customer
{
private string _name = "TEST";
public string Name
{
get { return this._name; }
set { this._name = value; }
}
}
public partial class UI: UserControl
{
public UI()
{
InitializeComponent();
Customer c = new Customer();
this.DataContext = c;
}
}
}
绑定代码(目标是文本框)如下所示:
<TextBox Name="MyTextBox" Text="{Binding Path=Name}" />
我希望文本框会显示TEST,但事实并非如此。文本框中没有任何内容。文档(数据绑定概述,绑定声明概述和绑定源概述)对我来说不是很清楚。
这是“输出”窗口中的错误消息:
BindingExpression path error: 'Name' property not found on 'object' ''ConfigurationSettings' (HashCode=36012562)'. BindingExpression:Path=Name; DataItem='ConfigurationSettings' (HashCode=36012562); target element is 'TextBox' (Name='MyTextBox'); target property is 'Text' (type 'String')
答案 0 :(得分:0)
马里奥是对的,所以你的代码应该是这样的:
namespace mynamespace
{
class Customer
{
private string _name = "TEST";
public string Name
{
get { return this._name; }
set { this._name = value; }
}
}
public partial class Window : UserControl
{
public Window()
{
InitializeComponent();
Customer c = new Customer();
this.DataContext = c;
}
}
}
答案 1 :(得分:0)
如果Customer c是DataContext,则不应该是:
<TextBox Name="MyTextBox" Text="{Binding Name}" />
答案 2 :(得分:0)
尝试实施INotifyPropertyChanged
界面并覆盖ToString()
课程中的Customer
:
public class Customer : INotifyPropertyChanged
{
private string _name = "TEST";
public string Name
{
get { return _name; }
set { _name = value; NotifyPropertyChanged("Name"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public override string ToString()
{
return Name;
}
}
然后,如果仍然不起作用,请尝试使用Name
构造函数中的值设置Window
属性,而不是内部的私有字段:
public Window()
{
InitializeComponent();
Customer c = new Customer() { Name = "TEST" };
this.DataContext = c;
}
答案 3 :(得分:0)
Customer c = new Customer();
this.DataContext = c;
到参数化构造函数,一切正常。
谢谢大家的帮助和抱歉这个愚蠢的错误。