【发布时间】:2016-10-03 22:42:34
【问题描述】:
我正在尝试创建一个包含项目列表的自定义组合框,并且每个项目都有一个添加(+)按钮,该按钮用于将该项目添加到“收藏夹”列表中:
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”
【问题讨论】:
-
这是我在回复中看到的。但也许是不正确的。源是一个依赖属性是的
-
添加了您要求的行。只是让我说,我猜来源不是问题,因为项目列出正确。问题是当我按下按钮时不会触发命令/动作
-
没问题。谢谢;)
-
我编辑并删除了那部分,正如我所说的,这是我在另一个案例中看到的,这是一个测试(没用)