Reputation: 8928
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?
Upvotes: 22
Views: 25472
Reputation: 725
To answer to your second question: Sometime can be useful to declare DataContext on XAML because you can see databinding at design time. If you declare it by code, the databinding will be done only at runtime.
There are other ways to achieve design time (fake) data. To learn more, please query about "bendability".
Note: As a general rule, please remember that if you have another question, you should create a new stackoverflow request :-)
Upvotes: 1
Reputation: 2401
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" });
}
}
Upvotes: 15
Reputation: 11051
It means "The DataContext is the Owner of this DataContext property" thus the control.
In C# it would be
myTextBox.DataContext = myTextBox;
Upvotes: 2