下一个代码按预期工作:
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; }
}
}
}
但是如果DataContext='{Binding RelativeSource={RelativeSource Self}}'
在 Window 标签和注释行中设置DataContext=this
设置,我们会得到一个空窗口。为什么?
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"));
}
...