C# WPF-自定义组合框中的绑定

C# WPF-自定义组合框中的绑定,c#,wpf,xaml,combobox,C#,Wpf,Xaml,Combobox,我正在尝试创建一个自定义组合框,其中包含一个项目列表,每个项目都有一个add(+)按钮,可以将该项目添加到“favorite”列表中: XAML: 然后在我的主视图中,使用组合框: <controls:ComboBoxWithButton Source="{Binding AvailableClients}" Selected="{Binding SelectedClient, Mode=TwoWay}"

我正在尝试创建一个自定义组合框,其中包含一个项目列表,每个项目都有一个add(+)按钮,可以将该项目添加到“favorite”列表中:

XAML:

然后在我的主视图中,使用组合框:

<controls:ComboBoxWithButton Source="{Binding AvailableClients}" Selected="{Binding SelectedClient, Mode=TwoWay}"
                                                       LostFocus="OnClientSelected"
                                                         CommandButton="{Binding AddFavoriteCommand}"/>

以及:

AddFavoriteCommand=newrelayCommand(AddToFavorite,f=>true);

但它不会触发我的函数“AddToFavorite”

按钮位于数据模板内,因此每个按钮的DataContext与UserControl的DataContext不同

您需要更改命令绑定以访问UserControl的DataContext:

    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Label Content="{Binding}" Width="250" />
            <Button Grid.Column="1" Command="{Binding CommandButton, RelativeSource={RelativeSource AncestorType=UserControl}}"
                    CommandParameter="{Binding Path=Selected}">+</Button>
        </Grid>
    </DataTemplate>

+

我在这里的回复中看到了这一点。但也许这是不对的。Source是一个独立的专有名词,请添加您要求的行。只是让我说,我想来源不是问题,因为项目是正确列出的。问题是当我按下按钮时不会触发Comand/Action无问题。谢谢;)我编辑并删除了该部分,正如我所说,这是我在另一个案例中看到的,这是一个测试(不起作用)
<controls:ComboBoxWithButton Source="{Binding AvailableClients}" Selected="{Binding SelectedClient, Mode=TwoWay}"
                                                       LostFocus="OnClientSelected"
                                                         CommandButton="{Binding AddFavoriteCommand}"/>
AddFavoriteCommand = new RelayCommand<object>(AddToFavorite, f => true);
    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Label Content="{Binding}" Width="250" />
            <Button Grid.Column="1" Command="{Binding CommandButton, RelativeSource={RelativeSource AncestorType=UserControl}}"
                    CommandParameter="{Binding Path=Selected}">+</Button>
        </Grid>
    </DataTemplate>