在 MainWindow 中,命令绑定工作正常。在 UserControl1 中它不起作用。请注意,数据上下文设置正确,这是绑定结果的按钮内容所证明的。
我不想将用户控件中的命令绑定到主窗口中的命令或任何其他此类诡计。我只是想复制我在 UserControl1 的 MainWindow 中所做的事情。
主窗口 XAML
<StackPanel>
<Button Content="Click Here" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
<local:UserControl1></local:UserControl1>
</StackPanel>
MainWindow 代码背后
public partial class MainWindow : Window
{
public static RoutedCommand ClickHereCommand { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
ClickHereCommand = new RoutedCommand();
CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
}
public void ClickHereExecuted(object sender, ExecutedRoutedEventArgs e)
{
System.Windows.MessageBox.Show("hello");
}
}
用户控件 XAML
<UserControl x:Class="CommandBindingTest.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" x:Name="root">
<Grid DataContext="{Binding ElementName=root}" >
<Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button>
</Grid>
</UserControl>
用户控制代码背后
public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
private string _ButtonContent;
public string ButtonContent
{
get { return _ButtonContent; }
set
{
if (_ButtonContent != value)
{
_ButtonContent = value;
OnPropertyChanged("ButtonContent");
}
}
}
public static RoutedCommand ClickHereCommand { get; set; }
public UserControl1()
{
InitializeComponent();
ClickHereCommand = new RoutedCommand();
CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted));
ButtonContent = "Click Here";
}
public void ClickHereExecuted(object sender, ExecutedRoutedEventArgs e)
{
System.Windows.MessageBox.Show("hello from UserControl1");
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}