简单类作为绑定数据源

时间:2018-02-27 13:45:59

标签: c# wpf

我是WPF的新手,想要创建数据绑定。 我做了一个演示项目,在我的MainWindow和运行时创建的子对象之间进行了双向数据绑定,这个子对象派生自UserControl,INotifyPropertyChanged带有一个TextBox。我的源是我的MainWindow上的私人列表。 {

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private List<Byte> buffer;

    public MainWindow()
    {
        Binding binding;
        binding = new Binding("Buffer");
        binding.ElementName = "window";
        binding.Mode = BindingMode.TwoWay;

        myEdit = new MyEdit();
        myEdit.SetBinding(MyEdit.BufferValueProperty, binding);
    }

    public List<Byte> Buffer
    {
        get
        {
            return this.buffer;
        }

        set
        {
            this.buffer = value;
            NotifyPropertyChanged("Buffer");
        }
    }

    private void NotifyPropertyChanged(String propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

现在我想将它实现到我的真实项目中。但是我的数据源不在MainWindow中,它在另一个没有XAML代码的简单类中。

{

public class SimpleClass: INotifyPropertyChanged
{
    private List<Byte> buffer;

    public event PropertyChangedEventHandler PropertyChanged;

    public SimpleClass()
    {
        this.buffer = new List<Byte>();

        Binding binding;
        binding = new Binding("Buffer");
        binding.ElementName = "?????????";
        binding.Mode = BindingMode.TwoWay;

        myEdit = new MyEdit();
        myEdit.SetBinding(MyEdit.BufferValueProperty, binding);
    }

}

我的问题是,我在哪里可以获取绑定的ElementName?是否有可能以这种方式做到这一点?

1 个答案:

答案 0 :(得分:0)

而不是ElementName直接设置Source。您还需要定义Buffer属性。绑定不会与某个领域合作。

public class SimpleClass: INotifyPropertyChanged
{
    private List<Byte> buffer;
    public List<Byte> Buffer { get { return buffer; } set { buffer = value; } }

    public event PropertyChangedEventHandler PropertyChanged;

    public SimpleClass()
    {
        this.buffer = new List<Byte>();

        Binding binding = new Binding("Buffer");
        binding.Source = this;
        binding.Mode = BindingMode.TwoWay;

        myEdit = new MyEdit();
        myEdit.SetBinding(MyEdit.BufferValueProperty, binding);
    }
}