【发布时间】:2017-03-04 18:33:11
【问题描述】:
如果我在构造函数中将 Window 的 DataContext 设置为 this,在 XAML 中将 Window 的 DataContext 设置为 {Binding RelativeSource={RelativeSource Self}},那么我可以看到 DataContext 引用了正确的对象实例(即 MainWindow)通过在代码隐藏的 Loaded 事件中放置一个断点。但是,Window 的子元素 exampleButton 的 Command 绑定为空。断言失败。
当我删除 XAML DataContext 设置(并且仅依赖于构造函数设置)时,exampleButton 的 Command 会正确使用 DataContext。
为什么XAML场景下exampleButton的Command绑定为null?
MainWindow.xaml
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Example"
SizeToContent="WidthAndHeight"
x:Name="mainWindow"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Loaded="mainWindow_Loaded">
<Button x:Name="exampleButton" Command="{Binding Path=ExampleCommand}" Content="Click"/>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public ICommand ExampleCommand { get; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
ExampleCommand = new DelegateCommand(x => { throw new ApplicationException(); });
}
private void mainWindow_Loaded(object sender, RoutedEventArgs e)
{
Debug.Assert(mainWindow == this);
Debug.Assert(mainWindow.DataContext == this);
Debug.Assert(exampleButton.DataContext == this);
Debug.Assert(exampleButton.Command == ExampleCommand); //<-- FAIL
}
}
【问题讨论】: