简体   繁体   中英

DataContext and binding self as RelativeSource

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?

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;

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM