[英]WPF - Binding in custom ComboBox
我正在尝试创建一个包含项目列表的自定义组合框,并且每个项目都有一个 add(+) 按钮,可以将该项目添加到“收藏夹”列表中:
XAML:
<UserControl x:Class=ComboBoxWithButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignWidth="300" Height="25">
<ComboBox
x:Name="ComboBoxBtn"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="0,0,0,-1"
Width="300"
ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding Path=Selected, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=UserControl}}">
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Content="{Binding}" Width="250" />
<Button Grid.Column="1" Command="{Binding CommandButton}"
CommandParameter="{Binding Path=Selected}">+</Button>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</UserControl>
XAML.CS:
public IEnumerable Source
{
get { return (IEnumerable)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(IEnumerable), typeof(ComboBoxWithButton), new PropertyMetadata(null));
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("CommandButton", typeof(ICommand), typeof(ComboBoxWithButton), new PropertyMetadata(null));
public ICommand CommandButton
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
然后在我的主视图中,使用我拥有的组合框:
<controls:ComboBoxWithButton Source="{Binding AvailableClients}" Selected="{Binding SelectedClient, Mode=TwoWay}"
LostFocus="OnClientSelected"
CommandButton="{Binding AddFavoriteCommand}"/>
和:
AddFavoriteCommand = new RelayCommand<object>(AddToFavorite, f => true);
但这并没有触发我的功能“AddToFavorite”
该按钮位于 DataTemplate 内,因此每个按钮的 DataContext 与 UserControl 的 DataContext 不同。
您需要更改 Command 绑定以访问 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.