Привязка к команде извне UserControl - PullRequest
4 голосов
/ 31 июля 2009

У меня есть простой UserControl, содержащий Label, ComboBox и Button. Короче говоря, он должен использоваться почти во всех моих представлениях много раз, каждый раз предоставляя разные ItemsSource и CreateItemCommand, используя привязки к моим свойствам ViewModel.

Label и ComboBox являются частью другого UserControl (LabeledComboBox), который прекрасно работает.

Проблема в том, что при попытке связать команду в окне, содержащем мой UserControl, я получаю следующее исключение:

Невозможно установить «Binding» в свойстве «CreateItemCommand» типа «MutableComboBox». «Связывание» может быть установлено только для свойства DependencyObject объекта Dependency.

Вот XAML для MutableComboBox:

<UserControl x:Class="Albo.Presentation.Templates.MutableComboBox"
x:Name="MCB"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:Albo.Presentation.Templates" >
<StackPanel Height="25" Orientation="Horizontal">
    <uc:LabeledComboBox x:Name="ComboBoxControl"
        Label = "{Binding ElementName=MCB, Path=Label}"
        ItemsSource="{Binding ElementName=MCB, Path=ItemsSource}"
        SelectedItem="{Binding ElementName=MCB, Path=SelectedItem}" />
    <Button x:Name="CreateItemButton"
        Grid.Column="1" Width="25" Margin="2,0,0,0"
        Content="+" FontFamily="Courier" FontSize="18" 
        VerticalContentAlignment="Center"
        Command="{Binding ElementName=MCB, Path=CreateItemCommand}"/>
</StackPanel>
</UserControl>

Вот код для него:

public partial class MutableComboBox : UserControl
{
    public MutableComboBox()
    {
        InitializeComponent();
    }

    public string Label
    {
        get { return this.ComboBoxControl.Label; }
        set { this.ComboBoxControl.Label = value; }
    }

    #region ItemsSource dependency property
    public static readonly DependencyProperty ItemsSourceProperty =
        ItemsControl.ItemsSourceProperty.AddOwner(
            typeof(MutableComboBox),
            new PropertyMetadata(MutableComboBox.ItemsSourcePropertyChangedCallback)
        );

    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    public static void ItemsSourcePropertyChangedCallback(
        DependencyObject controlInstance,
        DependencyPropertyChangedEventArgs e)
    {
        MutableComboBox myInstance = (MutableComboBox)controlInstance;

        myInstance.ComboBoxControl.ItemsSource = (IEnumerable)e.NewValue;
    } 
    #endregion // ItemsSource dependency property

    #region SelectedItem dependency property
    // It has just the same logic as ItemsSource DP.
    #endregion SelectedItem dependency property

    #region CreateItemCommand dependency property

    public static readonly DependencyProperty CreateItemCommandProperty =
        DependencyProperty.Register(
            "MutableComboBoxCreateItemCommandProperty",
            typeof(ICommand),
            typeof(MutableComboBox)
        );

    public ICommand CreateItemCommand
    {
        get { return (ICommand)GetValue(CreateItemCommandProperty); }
        set { SetValue(CreateItemCommandProperty,value); }
    }

    #endregion // CreateItem dependency property
}

Как видите, я использую два разных подхода к регистрации своих DP: ItemsSource берется из ItemsControl DP, а CreateItemCommand создается DependencyProperty.Register (...). Я пытался использовать Button.CommandProperty.AddOwner (...), но у меня было то же исключение.

Вот как я пытаюсь связать:

<Window ...
    xmlns:uc="clr-namespace:Albo.Presentation.Templates">
    <uc:MutableComboBox Label="Combo" 
        ItemsSource="{Binding Path=Recipients}"
        CreateItemCommand="{Binding Path=CreateNewRecipient}"/>
</Window>

Для DataContext окна задан соответствующий ViewModel, который предоставляет ObservableCollection получателей и ICommand CreateNewRecipient в качестве простых свойств.

Что я делаю не так? Единственное, что я хочу в этом конкретном случае, это предоставить свойство Button.Command для использования вне моего UserControl, так же как ItemsSource. Я пытаюсь использовать команды неправильно? Как я могу связать команды моего UserControls из других элементов управления или окон?

Считай меня новичком с этими вещами Command и DependencyProperty. Любая помощь будет оценена. Погуглил всю ночь и не нашел ничего полезного в моем случае. Простите мой английский.

1 Ответ

7 голосов
/ 31 июля 2009

Вы зарегистрировали неправильное имя для своего свойства зависимости. Должно быть:

public static readonly DependencyProperty CreateItemCommandProperty =
        DependencyProperty.Register(
            "CreateItemCommand",
            typeof(ICommand),
            typeof(MutableComboBox)
        );

Обратите внимание, что строка "CreateItemCommand". Вам следует прочитать эту документацию MSDN для получения подробной информации о соглашениях для свойств зависимостей.

...