使用按钮创建用户控件组合框

Create UserControl ComboBox with Button

我正在尝试创建一个 UserControl,它有一个带有项目列表的 ComboBox,然后我想添加一个按钮来执行某些操作。

我有这个代码:

ComboBoxWithButton XAML:

<ComboBox x:Name="ComboBoxBtn" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0,0,0,-1" Width="100" ItemsSource="{Binding Source}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Label Content="{Binding }" Width="100" />
                    <Button Grid.Column="1">Something</Button>
                </Grid>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

ComboBoxWithButton 代码:

public ComboBoxWithButton()
        {
            InitializeComponent();
        }


        public static readonly DependencyProperty SourceProprety =
            DependencyProperty.Register("Source", typeof(ObservableCollection<object>), typeof(ComboBoxWithButton), new PropertyMetadata(null));

        public ObservableCollection<object> Source
        {
            get { return (ObservableCollection<object>)GetValue(ValueProprety); }
            set { SetValue(ValueProprety, value); }
        }

然后在我的 Window 上调用:

<controls:ComboBoxWithButton Source="{Binding SomeCollection}"/>

但是组合框是空的

对您的依赖项进行三处更改 属性:将其类型更改为 System.Collections.IEnumerable(非通用),将 SourceProprety 的名称更正为 SourceProperty,然后使用SourceProperty 而不是 ValueProperty 在你对 GetValue()SetValue() 的调用中(最后一个错误不会影响 ComboBox,因为 Binding 会直接调用SetValue()GetValue(),还是有bug):

public static readonly DependencyProperty SourceProperty =
     DependencyProperty.Register("Source", 
         typeof(IEnumerable), 
         typeof(ComboBoxWithButton), 
         new PropertyMetadata(null));

public IEnumerable Source
{
    get { return (IEnumerable)GetValue(SourceProperty); }
    set { SetValue(SourceProperty, value); }
}

您对 属性 的定义要求集合的类型为 ObservableCollection<object>。只有 object,只有 object。如果您将 ObservableCollection<MyItem> 绑定到它,它将无法填充 ComboBoxComboBox.ItemsSourceSystem.Collections.IEnumerable 类型(属性 继承自 ItemsControl)。坚持下去。有用。任何 ObservableCollection 的任何东西都可以绑定到那个。让 ComboBox 弄清楚细节;这就是它最擅长的。

接下来,您的绑定正在查看 UserControlDataContext 以获得 Source 属性,但它是 [=] 的 属性 33=] 本身。解决方法如下:

<ComboBox 
    x:Name="ComboBoxBtn" 
    VerticalAlignment="Top" 
    HorizontalAlignment="Left" 
    Margin="0,0,0,-1" 
    Width="100" 
    ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"
    >

XAML 设计师可能会在 ItemsSource 行下方给您一个蓝色波浪线。让它呻吟,它有时会感到困惑。