2011-05-27 7 views

Respuesta

12

Para lograr esto, utilicé una clase derivada ExtendedComboBox que amplía la clase incorporada ComboBox. Puede encontrar el código fuente de esta clase en my blog post o inferior.

Después de agregar esta clase a su proyecto, puede utilizar este código XAML para mostrar un valor por defecto:

<local:ExtendedComboBox ItemsSource="{Binding ...Whatever...}" NotSelectedText="Select item..." /> 

Además, aquí es el test page con este control. Creo que el segundo combobox es eso lo que necesitas. example of the extended ComboBox

código completo de esta clase:

[TemplateVisualState(Name = ExtendedComboBox.StateNormal, GroupName = ExtendedComboBox.GroupItemsSource)] 
[TemplateVisualState(Name = ExtendedComboBox.StateNotSelected, GroupName = ExtendedComboBox.GroupItemsSource)] 
[TemplateVisualState(Name = ExtendedComboBox.StateEmpty, GroupName = ExtendedComboBox.GroupItemsSource)] 
public class ExtendedComboBox : ComboBox 
{ 
    public const string GroupItemsSource = "ItemsSourceStates"; 
    public const string StateNormal = "Normal"; 
    public const string StateNotSelected = "NotSelected"; 
    public const string StateEmpty = "Empty"; 

    private ContentPresenter selectedContent; 

    public ExtendedComboBox() 
    { 
     this.DefaultStyleKey = typeof(ComboBox); 
    } 

    public override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 
     this.selectedContent = this.GetTemplateChild("ContentPresenter") as ContentPresenter; 

     // This event can change the NotSelected state 
     this.SelectionChanged += (s, e) => this.SetTextIfEmpty(); 

     // Set a state at start 
     this.SetTextIfEmpty(); 
    } 

    // This method can change the Empty state 
    protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
    { 
     base.OnItemsChanged(e); 
     this.SetTextIfEmpty(); 
    } 

    /// <summary> 
    /// Text if the SelectedItem property is null. 
    /// </summary> 
    public string NotSelectedText 
    { 
     get { return (string)GetValue(NotSelectedTextProperty); } 
     set { SetValue(NotSelectedTextProperty, value); } 
    } 

    public static readonly DependencyProperty NotSelectedTextProperty = 
     DependencyProperty.Register("NotSelectedText", typeof(string), typeof(ExtendedComboBox), new PropertyMetadata(" ")); 

    /// <summary> 
    /// Text if there are no items in the ComboBox at all. 
    /// </summary> 
    public string EmptyText 
    { 
     get { return (string)GetValue(EmptyTextProperty); } 
     set { SetValue(EmptyTextProperty, value); } 
    } 

    public static readonly DependencyProperty EmptyTextProperty = 
     DependencyProperty.Register("EmptyText", typeof(string), typeof(ExtendedComboBox), new PropertyMetadata(null)); 

    /// <summary> 
    /// Changes the state of this control and updates the displayed text. 
    /// </summary> 
    protected void SetTextIfEmpty() 
    { 
     if (this.selectedContent == null || !(this.selectedContent.Content is TextBlock)) 
      return; 
     var text = this.selectedContent.Content as TextBlock; 

     if (this.SelectedItem == null && this.Items != null && this.Items.Count > 0) 
     { 
      text.Text = this.NotSelectedText; 
      VisualStateManager.GoToState(this, ExtendedComboBox.StateNotSelected, true); 
     } 
     else if (this.SelectedItem == null) 
     { 
      text.Text = this.EmptyText ?? this.NotSelectedText; 
      VisualStateManager.GoToState(this, ExtendedComboBox.StateEmpty, true); 
     } 
     else VisualStateManager.GoToState(this, ExtendedComboBox.StateNormal, true); 
    } 
} 
+1

Muchas gracias, se resolvió el problema –

+0

¿Hay una manera fácil para que el usuario para seleccionar el estado "No seleccionado" después de que se haya hecho una selección? – Jordan

+0

@Jordan Simplemente establezca '.SelectedItem = null;' – vorrtex

0

a hacer esto:

theComboBox.SelectedItem = yourDataItem; 

alternativamente, establecer el índice seleccionado:

theComboBox.SelectedIndex = 0; 

Editar

Si ItemSource está obligado, desea anular de DataContextChanged el combo y luego use una de las líneas anteriores para establecer el índice/elemento seleccionado.


Sin embargo, si no desea que el texto predeterminado para que sea seleccionable, tendrá que hacer algo en la línea de this.

+0

estoy vinculante el menú desplegable para un contexto de datos :( –

Cuestiones relacionadas