gpt4 book ai didi

c# - DataContext 并将自身绑定(bind)为 RelativeSource

转载 作者:可可西里 更新时间:2023-11-01 03:01:20 24 4
gpt4 key购买 nike

有人可以向我解释以下 XAML 行吗?

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

Here简单的使用示例。

如何用 C# 代码替换该行?

最佳答案

这只是将 DataContext 属性设置为等于具有该属性的对象。等效代码为 this.DataContext = this;

编辑

DataContext 属性是用作此对象及其子对象上发生的所有绑定(bind)的上下文的对象。如果您没有将 DataContext 正确设置为要绑定(bind)到的模型,则所有绑定(bind)都将失败。

编辑2

以下是如何在后面的代码中设置它(与您的示例匹配):

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

关于c# - DataContext 并将自身绑定(bind)为 RelativeSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12430615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com