Search code examples
wpfxaml-binding

WPF- Bind object property to control in xaml


I have clearly stated my issue below.

Thank you in advance -->

I have a public class:

public class class1
{
 int iVal;
 public int IVal
 {
  get { return iVal; }
  set { iVal=value;  }
 }
}

I am going to create an object of type class1 inside my mainWindow.cs.

class1 ob = new class1();

In the mainWindow.xaml file I have a TextBlock.

My question is how to bind the ob.IVal value to the TextBlock using XAML binding.

<TextBlock Text="{Binding IVal, Mode=OneWay}"/>   
// this binding is not working for me.

Solution

  • It looks like you just need to set the DataContext for the XAML tree. In mainWindow.cs, write it like this:

    public partial class MainWindow : Window
    {
        public class1 ob { get; set; }
    
        public MainWindow()
        {
            ob = new class1();
            InitializeComponent();
            this.DataContext = ob;
        }
    }
    

    Then the binding to IVal should work.