我有自己的自定义组合框,最后一项为按钮,命令为:
代码:
public class CustomComboBox : ComboBox
{
public static readonly DependencyProperty ButtonCommandProperty =
DependencyProperty.Register("ButtonCommand", typeof (ICommand), typeof (CustomComboBox), null);
public ICommand ButtonCommand
{
get { return (ICommand) GetValue(ButtonCommandProperty); }
set { SetValue(ButtonCommandProperty, value); }
}
}
样式:
<Style TargetType="{x:Type controls:CustomComboBox}">
<Style.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="Height" Value="16" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock Text="{TemplateBinding Content}" Background="Transparent" Foreground="#CCCCCD" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Style.Resources>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type controls:CustomComboBox}">
<StackPanel>
<ComboBox
SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type controls:CustomComboBox}},
UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding ItemsSource, Mode=OneWay,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type controls:CustomComboBox}},
UpdateSourceTrigger=PropertyChanged}">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<TextBlock Style="{StaticResource TextBlockDimmed}" Text="{Binding Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger
Binding="{Binding Converter={converters:ComboBoxItemIndexToStringConverter},
RelativeSource={RelativeSource Self}}" Value="IsLastItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<Button Content="{Binding}"
Command="{Binding ButtonCommand,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type controls:CustomComboBox}}}" />
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
使用:
<controls:CustomComboBox Grid.Column="1"
SelectedItem="{Binding Path=SelectedAreaName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ButtonCommand="{Binding CreateNewAreaCommand}"
ItemsSource="{Binding AreasNamesList, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
当我尝试多次调用programm中的按钮命令(单击按钮)时,我收到一条错误消息:
'Specified element is already the logical child of another element. Disconnect it first.'
我猜XAML风格的问题,但我不确定问题是什么。