wpf xaml绑定到后面的代码中创建的对象

时间:2013-11-14 15:42:45

标签: c# wpf xaml binding

刚开始我对C#和xaml很新。

我已经看过,检查了教程,关于绑定,但我看到的大部分内容都在xaml中创建了一个对象。但是,我想在代码中创建对象,然后绑定到它的属性。此外,我将在稍后的代码中定义几个对象。一般来说,我想绑定到文本框。

一般来说,我的代码看起来像这样:

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    MyTestObject myTestObject;

    public MainWindow()
    {
        myTestObject= new MyTestObject ();
        this.DataContext = this;
        InitializeComponent();

    }
}

MyTestObject .cs

class MyTestObject : INotifyPropertyChanged
{
    public MyTestObject ()
    {

    }

    private string testString = "Test";
    public string TestString
    {
        get { return testString; }
        set
        {
            if (value == testString) return;
            testString = value;
            this.OnPropertyChanged("TestString");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
    }
}

最终我将拥有相当多的(数字)属性,这些属性将显示在多个文本框中,因为该软件旨在作为发送测量数据的外部硬件组件的接口。我尝试了几种绑定方式,但我还没有成功。我非常感谢如何将前面提到的属性绑定到TextBox

1 个答案:

答案 0 :(得分:18)

将Datacontext设置为myTestObject。或者,为myTestObject创建一个公共属性,并将您的Xaml绑定设置为{Binding MyTestObjectPropertyHere.TestString}

例如:

public partial class MainWindow : Window
{
    MyTestObject myTestObject;

    public MainWindow()
    {
        myTestObject = new MyTestObject ();

        this.DataContext = myTestObject;

        InitializeComponent();

    }
}

<强>的Xaml

<TextBox Text="{Binding Path=TestString}" />

作为datacontext绑定到MainWindow的示例:

public partial class MainWindow : Window
{
    MyTestObject myTestObject;

    public MyTestObject MyTestObjectProperty { get { return myTestObject; } }

    public MainWindow()
    {
        myTestObject = new MyTestObject ();

        this.DataContext = this;

        InitializeComponent();

    }
}

<强>的Xaml

<TextBox Text="{Binding Path=MyTestObjectProperty.TestString}" />