Как использовать привязки команд в пользовательских элементах управления в wpf?
В MainWindow привязка команд работает нормально. В UserControl1 это не работает. Обратите внимание, что текст данных установлен правильно, о чем свидетельствует содержание кнопки, которая является результатом привязки.
Я не пытаюсь связать команду в пользовательском контроле с командой в главном окне или любым другим подобным обманом. Я просто пытаюсь повторить то, что я сделал в MainWindow в UserControl1.
MainWindow XAML
Код основного окна позади
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");
}
}
UserControl XAML
Код контроля пользователя позади
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
}