c# – 在构造函数中设置DataContext = this和在WPF中绑定到{RelativeSource Self}之间的区别?
作者:互联网
下一代码按预期工作:
AskWindow.xaml:
<Window
x:Class='AskWPF.AskWindow'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
>
<DataGrid ItemsSource="{Binding SimpleItems}" />
</Window>
AskWindow.xaml.cs:
namespace AskWPF {
public class SimpleRow {
private string firstColumn;
private string secondColumn;
public SimpleRow(string first, string second) {
firstColumn = first;
secondColumn = second;
}
public string FirstColumn {
get { return firstColumn; }
set { firstColumn = value; }
}
public string SecondColumn {
get { return secondColumn; }
set { secondColumn = value; }
}
}
public partial class AskWindow : Window {
private ObservableCollection<SimpleRow> simpleItems;
public AskWindow() {
InitializeComponent();
DataContext = this;
simpleItems = new ObservableCollection<SimpleRow>();
simpleItems.Add(new SimpleRow("row 0, column 0", "row 0, column 1"));
simpleItems.Add(new SimpleRow("row 1, column 0", "row 1, column 1"));
}
public ObservableCollection<SimpleRow> SimpleItems {
get { return simpleItems; }
}
}
}
但是如果在Window标签和注释行DataContext =中设置DataContext ='{Binding RelativeSource = {RelativeSource Self}}’,我们会得到一个空窗口.为什么?
AskWindow.xaml:
<Window .... DataContext='{Binding RelativeSource={RelativeSource Self}}'>
<DataGrid ItemsSource="{Binding SimpleItems}" />
</Window>
AskWindow.xaml.cs:
...
public AskWindow() {
InitializeComponent();
// DataContext = this;
simpleItems = new ObservableCollection<SimpleRow>();
simpleItems.Add(new SimpleRow("row 0, column 0", "row 0, column 1"));
simpleItems.Add(new SimpleRow("row 1, column 0", "row 1, column 1"));
}
...
解决方法:
这是我的猜测.在这两种情况下,您的Collection都是空的.确切地说,在InitializeComponent之后.此时,初始数据绑定获取数据,但没有datacontext.现在,通过设置DataContext,您的属性将被引发,并且与之相关的每个绑定都会失效并刷新.这是我的猜测部分,它的工作原理是延迟了对ItemsSource的绑定,因此它只是在下一行设置集合.
简而言之:设置Datacontext将重新绑定绑定.但是在您的RelativeSource示例中,您的绑定从一开始就起作用,但该集合为null,您从未告诉wpf重新绑定绑定.
如果你直接初始化你的收藏它应该工作正常.
标签:c,wpf,xaml,datacontext,relativesource 来源: https://codeday.me/bug/20190703/1368094.html