1

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. 

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response it was really help for me. I have one more question. If I have the testblock inside a grid. Can I set the data context to grid (grid.DataContext=ob;) to solve my issue rather than setting it to window or the textblock?
@dash yes, that's correct, you can set the data context to the Grid.
1

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 .

Comments