javirs javirs - 3 months ago 18
C# Question

Binding to a class member

This one seems to be basic and somehow it can be duplicated but no one of the answers I found on the internet made the thing work for me ..

I want to bind elements from my UI (XAML) to members of instances of classes I have.
So, lets have a simple XAML

<Window x:Class="gUSBampReader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="601" Width="857" xmlns:my="clr-namespace:binding;assembly=binding">

<TextBlock Name="UITextBlock"/> <!-- THIS IS THE TEXT BOX TO BE BINDED -->

</Window>


And on the other side I have a class

public class foo
{
objectThatImplementsINotify a; //lets say that's equivalent to an string
}

public partial class mainWindow : Window
{
public foo externalMembers;

public mainWindow()
{
externalMembers = new foo();
//Let's show externalMembers.a in UITextBlock!
}
}


I would like to learn how to do this binding both from XAML and from C#. Because some times external members is there and I can bind at developing time but other times is dynamic and it must be created and binded in execution time

And finally .. can you recommend a good tutorial on dataBinding with some examples ? There is a lot of stuff for XAML (but I've been unable to make it work). But not too much for C#.

Thanks in advance !!!

Answer

You would need to set the DataContext of your window to itself:

public mainWindow()
{
   externalMembers = new foo();
   DataContext = this;
   //Let's show externalMembers.a in UITextBlock!
}

And then you need to bind the textblock:

<TextBlock Name="UITextBlock" Text="{Binding externalMembers.a}"/>

To make it work you further need to change externalMembers.a to be a property, not a field:

public class foo
{
    objectThatImplementsINotify a { get; set; }
}
Comments