我希望扩展WPF Combobox,使组合框旁边显示两个按钮。我无法使用UserControl,因为我需要在纯xaml中指定组合框的项目,如下所示:
<CustomComboBox>
<CustomComboBoxItem />
<CustomComboBoxItem />
</CustomComboBox>
我非常害怕采用组合框的模板并对其进行扩展,因为对于组合框而言,它非常庞大且复杂。我正在寻找一个简单而简单的解决方案来创建类似ComboBox的ItemsControl
,只需要连接两个按钮。建议欢迎!
答案 0 :(得分:3)
修改:使用UserControl
:
的Xaml:
<UserControl x:Class="Test.CustomComboBox"
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:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal">
<ComboBox Name="_comboBox" Margin="5"/>
<Button Content="_Apply" Padding="3" Margin="5" Click="Button_Apply_Click"/>
<Button Content="_Reset" Padding="3" Margin="5" Click="Button_Reset_Click"/>
</StackPanel>
</UserControl>
代码:
[ContentProperty("Items")]
public partial class CustomComboBox : UserControl
{
public event RoutedEventHandler ApplyClick;
public event RoutedEventHandler ResetClick;
public ItemCollection Items
{
get { return _comboBox.Items; }
set
{
_comboBox.Items.Clear();
foreach (var item in value)
{
_comboBox.Items.Add(item);
}
}
}
public CustomComboBox()
{
InitializeComponent();
}
private void Button_Apply_Click(object sender, RoutedEventArgs e)
{
if (ApplyClick != null)
{
ApplyClick(sender, e);
}
}
private void Button_Reset_Click(object sender, RoutedEventArgs e)
{
if (ResetClick != null)
{
ResetClick(sender, e);
}
}
}
用法:
<local:CustomComboBox ApplyClick="Button2_Click">
<ComboBoxItem Content="Item1"/>
<ComboBoxItem Content="Item2"/>
<ComboBoxItem Content="Item3"/>
</local:CustomComboBox>
外观:
UserControl应该可以正常运行,您仍然可以在Xaml标记中指定项目,例如如果我有时间用户控制我可以这样做:
[ContentProperty("Hours")]
public partial class TimeBox : UserControl
{
public string Hours
{
get { return this.TBHours.Text; }
set { this.TBHours.Text = value; }
}
...
}
这样你可以在XAML中设置小时数:
<local:TimeBox>
<sys:String>24</sys:String>
</local:TimeBox>
您应该能够对此进行调整以设置ComboBox的项目。