編輯:
的Xaml:使用UserControl
Conrete例如
<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>
外觀:
![enter image description here](https://i.stack.imgur.com/gJJwz.png)
一個用戶控件應該做的罰款,你還可以指定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>
你應該能夠適應這個設置你的組合框的項目。
如果UserControl不好,並且不可能複製粘貼這兩個按鈕 - 自定義控件只是實現此目的的一種方法。 – vorrtex 2011-04-01 19:17:50