Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf xaml binding to object created in code behind

Tags:

c#

binding

wpf

xaml

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.

like image 430
xnonamex Avatar asked Nov 14 '13 15:11

xnonamex


1 Answers

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}" />
like image 197
Michael G Avatar answered Nov 04 '22 17:11

Michael G