-2

I'm pretty new to WPF, and can't figure out how to bind to the property of an object. I've read through a bunch of the other answers to similar questions, but can't get it working.

I have my form designed how I want it. In Winforms, I wrote code behind it to create the bindings whenever the property is assigned. I could still do that here, but want to learn how to do it 'natively' in WPF if possible.

Here is my custom control I'm setting up:

public class Robot 
{
    // This has been heavily reduced for the example, but there are about 50 properties to bind to
    public string SerialNumber {get;}
    public string WorkOrderNumber {get;}
}

public partial class Robot_DetailDisplay : UserControl
    {
        public Robot_DetailDisplay()
        {
            InitializeComponent();
        }

         // Additional property that was added to the control - will be assigned via a public method
        public Robot Robot { get; private set; }
}

and the XAML I have for a textbox:

<TextBox x:Name="Txt_SerialNum" Grid.Row="3" Grid.Column="4" Template="{StaticResource InfoBoxTemplate}"/>

How can I bind to the Serial Number property? -- The property accessible in code via: this.Robot.SerialNumber, but I don't know how/if I can bind to it using the xaml directly.

Specifically, I'm wondering if it will allow browsing the Robot properties in the binding intellisense windows when writing the xaml, instead of having to know the full path to each property by memory/copy-paste.

RFBomb
  • 33
  • 5
  • If you want to bind to a property of the control it self, you should set it's `DataContext`. Here is a tutorial: [Using the DataContext](https://wpf-tutorial.com/data-binding/using-the-datacontext/) – Jeroen van Langen May 25 '22 at 14:35
  • Also read [Data binding overview](https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-6.0). – Clemens May 25 '22 at 14:38
  • Ok, both of those helped me get further, But I still don't know how to bind to the Robot property that has been added to the form. What I was able to set up is creating a static binding in the `Resources` section and refer to that. But that isn't visible via the backend code from what I can tell, so I don't know how to tell it to refresh – RFBomb May 25 '22 at 14:48

0 Answers0