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?
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.
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 ...
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" });
}
}
It means "The DataContext is the Owner of this DataContext property" thus the control.
In C# it would be
myTextBox.DataContext = myTextBox;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With