简体   繁体   中英

wpf xaml binding to object created in code behind

Just to start off I am quite new to C# and xaml.

I have watched, checked tutorials, about binding, but most of what I have seen create an object in the xaml. However I want to create the object in the code and then bind to it's properties. Furthermore I will have several objects defined in code later on. In general I want to bind to text boxes.

In general my code looks something like this:

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));
    }
}

Eventually I will have quite a lot of (numerical) properties, which will be displayed in several text boxes, because the software is intended as an interface to an external hardware component that sends measured data. I have tried several ways of binding but I have not succeeded yet. I would be most grateful for an example how to bind the previously mentioned property to a TextBox .

Set the Datacontext to myTestObject. Or, make a public property for myTestObject and set your Xaml binding to {Binding MyTestObjectPropertyHere.TestString}

For example:

public partial class MainWindow : Window
{
    MyTestObject myTestObject;

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

        this.DataContext = myTestObject;

        InitializeComponent();

    }
}

Xaml

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

Example with binding to the MainWindow as the datacontext:

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}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM