简体   繁体   English

DataContext和绑定self作为RelativeSource

[英]DataContext and binding self as RelativeSource

Can someone explain me the following XAML line? 有人能解释我下面的XAML系列吗?

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

Here the simple example of use. 这里是简单的使用示例。

How to replace that line with a C# code? 如何用C#代码替换该行?

That simply sets the DataContext property equal to the object with the property. 这只是将DataContext属性设置为等于具有该属性的对象。 The code equivalent would be this.DataContext = this; 等价的代码是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. DataContext属性是用作此对象及其子对象上发生的所有绑定的上下文的对象。 If you don't have a DataContext correctly set to the model you want to bind to, all of your bindings will fail. 如果没有将DataContext正确设置为要绑定的模型,则所有绑定都将失败。

Edit2 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. 这意味着“DataContext是此DataContext属性的所有者”,因此控件。

In C# it would be 在C#中它会是

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. 回答你的第二个问题:有时在XAML上声明DataContext是有用的,因为你可以在设计时看到数据绑定。 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 :-) 注意:作为一般规则,请记住,如果您有其他问题,您应该创建一个新的stackoverflow请求:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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