为什么在XAML中绑定MainWindow datacontext的行为与使用this.datacontext = this的代码隐藏中的绑定相同?

我正在尝试使用Data绑定将ObservableCollection绑定到DataGrid的ItemsSource,因为我了解了WPF和其他内容。

在代码隐藏中,我可以使用this.DataContext = this;设置DataContext this.DataContext = this;bloopDataGrid.DataContext = this; 。 这很好,花花公子。

我以为我可以尝试类似的东西

    

在我的主窗口中,但这会导致Stack Overflowexception,如本问题中所述 。 很好,这是有道理的。

在阅读了这个以及在窗口的XAML代码中尝试DataContext="{Binding RelativeSource={RelativeSource Self}}"其他问题/答案之后,我想我实际上可以做到这一点 。 显然我做不到 。 或者至少,IDE让我和它的语法正确,但不做我想要的(即,究竟是什么this.DataContext = this; )。

然后我读到这个关于使用"{Binding ElementName=, Path=}"并试图像这样使用它:

   

哪个也行不通。 也许不是出于同样的原因,但我无法弄清楚它的问题。

奇怪的是,我无法复制Rachel Lim博客文章中显示的重新绑定示例。

XAML:

            

C#:

 using System; using System.Collections.ObjectModel; //For ObservableCollection using System.Windows; namespace DataBinding { public partial class MainWindow : Window { public String text { get; set; } public ObservableCollection OutputCollection { get; set; } public struct testStruct { public testStruct(String x, String y) : this() { Col1 = x; Col2 = y; } public String Col1 { get; set; } public String Col2 { get; set; } } public MainWindow() { InitializeComponent(); testA t1 = new testA(); this.DataContext = this; //this.DataContext = t1; //bloopDataGrid.DataContext = this; text = "bound \"this\""; t1.text = "bound a class"; OutputCollection = new ObservableCollection(); OutputCollection.Add(new testStruct("1", "2")); OutputCollection.Add(new testStruct("3", "4")); } public class testA { public String text { get; set; } } } } 

上面的代码是我用来测试它的,目前正在使用正确给我的代码隐藏版本

在代码隐藏中

我做错了什么,这使我无法获得与上图相同的结果,但是使用XAML进行DataContext处理? 我没有正确连接点吗? ……我错过了一些点吗?

    

是不一样的

 this.DataContext = this; 

第一个是创建MainWindow类的新实例并将其分配给WindowDataContext属性,而第二个实例是将Window同一个实例分配给其DataContext属性。

为了在XAML中实现这一点,您需要使用RelativeSource绑定:

   

编辑:

在XAML和后面的代码中定义DataContext之间的行为差​​异是由于在构造函数完成执行时实际解析了XAML这一事实,因为Dispatcher等待用户代码(在Window的构造函数中)完成之前执行其待处理的操作。

这会导致实际属性值在这些不同时刻不同,并且由于没有INotifyPropertyChanged ,WPF无法更新UI以反映新值。

couldWindow本身中实现INotifyPropertyChanged ,但我建议为此创建一个ViewModel,因为我不喜欢将INotifyPropertyChanged (更多是ViewModel概念)与DependencyObject派生类(UI元素)混合的事实。