Wpf 从UserControl外部绑定到命令

Wpf 从UserControl外部绑定到命令,wpf,button,user-controls,command,Wpf,Button,User Controls,Command,我有一个简单的用户控件,包含标签、组合框和按钮。简言之,它将在我的几乎所有视图中多次使用,每次使用绑定到我的ViewModel属性的不同ItemsSource和CreateItemCommand提供 Label和ComboBox是另一个用户控件(LabeledComboBox)的一部分,该控件工作正常 问题是,当我尝试在包含UserControl的窗口中绑定命令时,会出现以下异常: 无法在“MutableComboBox”类型的“CreateItemCommand”属性上设置“Binding”。

我有一个简单的用户控件,包含标签、组合框和按钮。简言之,它将在我的几乎所有视图中多次使用,每次使用绑定到我的ViewModel属性的不同ItemsSource和CreateItemCommand提供

Label和ComboBox是另一个用户控件(LabeledComboBox)的一部分,该控件工作正常

问题是,当我尝试在包含UserControl的窗口中绑定命令时,会出现以下异常:

无法在“MutableComboBox”类型的“CreateItemCommand”属性上设置“Binding”。只能对DependencyObject的DependencyProperty设置“绑定”

以下是可变组合框的XAML:

<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>
如您所见,我使用两种不同的方法来注册DPs: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的命令


考虑到我是一个拥有命令和依赖属性的新手。任何帮助都将不胜感激。谷歌搜索了一整夜,在我的情况下没有发现任何有用的东西。请原谅我的英语。

您为依赖项属性注册了错误的名称。应该是:

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

注意字符串是“CreateItemCommand”。有关依赖项属性约定的详细信息,请通读。

谢谢!就这样。假设我需要更多地了解它的工作原理。我唯一知道的是,它在名称空间中必须是唯一的。那么DependencyProperty.Register()中的名称的标准是什么?只是在声明中从name中删除Property这个词还是别的什么?没问题。我在我的答案中添加了一个链接,可以帮助您理解这一点。该链接不再可用。
public static readonly DependencyProperty CreateItemCommandProperty =
        DependencyProperty.Register(
            "CreateItemCommand",
            typeof(ICommand),
            typeof(MutableComboBox)
        );