Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataContext and binding self as RelativeSource

Tags:

Can someone explain me the following XAML line?

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Here the simple example of use.

How to replace that line with a C# code?

like image 535
gliderkite Avatar asked Sep 14 '12 19:09

gliderkite


People also ask

What is a Datacontext?

Data context is the network of connections among data points. Those connections may be created as metadata or simply identified and correlated. Contextual metadata adds value, essentially making it possible to receive information from data. A single data point on its own is useless.

What is relative source?

The RelativeSource is a markup extension that is used in particular binding cases when we try to bind a property of a given object to another property of the object itself, when we try to bind a property of a object to another one of its relative parents, when binding a dependency property value to a piece of XAML in ...


2 Answers

That simply sets the DataContext property equal to the object with the property. The code equivalent would be this.DataContext = this;

Edit

The DataContext property is the object that is used as the context for all the bindings that occur on this object and its child objects. If you don't have a DataContext correctly set to the model you want to bind to, all of your bindings will fail.

Edit2

Here is how to set it in code behind (matching your example):

public partial class ListViewTest : Window
{
    ObservableCollection<GameData> _GameCollection = 
        new ObservableCollection<GameData>();

    public ListViewTest()
    {
        _GameCollection.Add(new GameData { 
          GameName = "World Of Warcraft", 
          Creator = "Blizzard", 
          Publisher = "Blizzard" });
        _GameCollection.Add(new GameData { 
          GameName = "Halo", 
          Creator = "Bungie", 
          Publisher = "Microsoft" });
        _GameCollection.Add(new GameData { 
          GameName = "Gears Of War", 
          Creator = "Epic", 
          Publisher = "Microsoft" });

        InitializeComponent();

        this.DataContext = this;   //important part
    }

    public ObservableCollection<GameData> GameCollection
    { get { return _GameCollection; } }

    private void AddRow_Click(object sender, RoutedEventArgs e)
    {
      _GameCollection.Add(new GameData { 
          GameName = "A New Game", 
          Creator = "A New Creator", 
          Publisher = "A New Publisher" });
    }
}
like image 191
Dylan Meador Avatar answered Sep 21 '22 18:09

Dylan Meador


It means "The DataContext is the Owner of this DataContext property" thus the control.

In C# it would be

myTextBox.DataContext = myTextBox;
like image 25
dowhilefor Avatar answered Sep 23 '22 18:09

dowhilefor