У меня есть UserControl, который содержит кнопку и некоторые другие средства управления:
<UserControl>
<StackPanel>
<Button x:Name="button" />
...
</StackPanel>
</UserControl>
Когда я создаю новый экземпляр того управления, я хочу достигнуть свойство Button's Command:
<my:GreatUserControl TheButton.Command="{Binding SomeCommandHere}">
</my:GreatUserControl>
Конечно, "TheButton. Команда" вещь не работает.
Таким образом, мой вопрос: Используя XAML, как я могу установить.Command свойство кнопки в моем пользовательском элементе управления?
Добавьте свойство dependency к вашему UserControl и привяжите к нему свойство Command кнопки.
Итак, в вашем GreatUserControl:
public ICommand SomeCommand
{
get { return (ICommand)GetValue(SomeCommandProperty); }
set { SetValue(SomeCommandProperty, value); }
}
public static readonly DependencyProperty SomeCommandProperty =
DependencyProperty.Register("SomeCommand", typeof(ICommand), typeof(GreatUserControl), new UIPropertyMetadata(null));
И в XAML вашего GreatUserControl:
<UserControl
x:Class="Whatever.GreatUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="me"
>
<Button Command="{Binding SomeCommand,ElementName=me}">Click Me!</Button>
</UserControl>
Таким образом, ваша кнопка привязывается к команде на самом UserControl. Теперь вы можете установить это в родительском окне:
<my:GreatUserControl SomeCommand="{Binding SomeCommandHere}" />