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.
有帮助吗?

解决方案

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.

其他提示

Probably you missed to set the DataContext property - as dbasemen suggested - but it's still not enough.

You set the binding mode to OneWay which means that the communication goes from the source to the target: Class1.IVal -> TextBlock.Text in this case.

But you have to send notification about the changes of the IVal property, which means you have to implement the INotifyPropertyChanged event handler and raise the Propertychanged event when the IVal prop is set.

You find here how to do it .

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top