1

I've read the online document about data binding but still couldn't make it work. I simply want to understand data binding and do things the way it should.

Here is my code in my 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;
       }
   }
}

The binding code (target is a textbox) looks like this:

<TextBox Name="MyTextBox" Text="{Binding Path=Name}" />

I expect the textbox will show TEST, but it doesn't. There is nothing in the textbox. The documentation (Data Binding Overview, Binding Declarations Overview, and Binding Sources Overview) is not very clear to me.

This is the error message from the Output window:

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')
4

4 回答 4

1

我真是个白痴!我有两个构造函数,一个默认构造函数和一个参数化构造函数。我正在调用参数化构造函数。移动代码后:

       Customer c = new Customer();
       this.DataContext = c;

对于参数化的构造函数,一切正常。

感谢大家的帮助,并对这个愚蠢的错误感到抱歉。

于 2013-09-09T19:51:59.437 回答
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;
       }
   }
}
于 2013-09-09T08:50:20.933 回答
0

如果客户 c 是 DataContext 不应该是:

 <TextBox Name="MyTextBox" Text="{Binding Name}" />
于 2013-09-09T09:01:18.253 回答
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;
}
于 2013-09-09T09:51:50.820 回答