2011-04-01 63 views
2

我想以兩個按鈕顯示在組合框旁邊的方式擴展WPF組合框。我不能用一個用戶控件,因爲我需要指定這樣的組合框的純XAML的項目:使用按鈕擴展組合框

<CustomComboBox> 
    <CustomComboBoxItem /> 
    <CustomComboBoxItem /> 
</CustomComboBox> 

我很害怕採取組合框的模板和擴展它,因爲組合框是非常大而且複雜。我正在尋找一種簡單而簡單的解決方案來創建類似組合框的ItemsControl,只需連接兩個按鈕即可。建議歡迎!

+1

如果UserControl不好,並且不可能複製粘貼這兩個按鈕 - 自定義控件只是實現此目的的一種方法。 – vorrtex 2011-04-01 19:17:50

回答

3

編輯:

的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


一個用戶控件應該做的罰款,你還可以指定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> 

你應該能夠適應這個設置你的組合框的項目。

+0

這可以通過具有ContentPresenter的控件完成。它不適用於ItemsControls。 – Falcon 2011-04-01 13:09:32

+0

我不太明白你的意思,我用一個工作示例更新了我的答案...... – 2011-04-01 13:26:34

+0

我承認這樣做,但我無法爲使用此方法的ComboBoxItems提供x:Name屬性。 :( – Falcon 2011-04-01 13:40:32