Search code examples
c#xamldata-bindingdatacontext

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?


Solution

  • 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" });
        }
    }