2016-04-30 2 views
0

Как определить пользовательский шаблон для ComboBox в моей UWP App для раскрывающегося мне нужен флажок с меткой, но когда пользователь выбирает любой вариант я просто нужно показать этикетку в comoboxКак создавать различный ComboBox ItemTemplate для выпадающего списка

Я попробовал это, но я не работал:

<ComboBox x:Name="cbCountry" 
         Header="Country" 
         Margin="10,5" 
         HorizontalAlignment="Stretch" 
         Style="{StaticResource ComboBoxStyle}"> 
       <ComboBox.ItemTemplate> 
        <DataTemplate> 
         <CheckBox Content="{Binding}"></CheckBox> 
        </DataTemplate> 
       </ComboBox.ItemTemplate> 
       <ComboBox.ItemsPanel> 
        <ItemsPanelTemplate> 
         <TextBlock Text="{Binding}"/> 
        </ItemsPanelTemplate> 
       </ComboBox.ItemsPanel> 

+0

Используйте только один шаблон и видимость окна могут быть обработаны в зависимости от того, является ли он SelectedItem или нет. Вы можете использовать конвертер для этого – Archana

+0

Я новичок в UWP, некоторая демо-версия кода будет полезна. –

+0

Хорошо. Я добавлю образец через некоторое время. – Archana

ответ

1
<Page.Resources> 
     <local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> 
</Page.Resources> 
<ComboBox x:Name="cbState" DropDownClosed="cbState_DropDownClosed" DropDownOpened="cbState_DropDownOpened" Margin="75,287,0,0" Width="169" ItemContainerStyle="{StaticResource ComboBoxItemStyle1}" Style="{StaticResource ComboBoxStyle1}" > 

       <ComboBox.ItemTemplate> 
        <DataTemplate> 
        <StackPanel> 
         <CheckBox Content="{Binding}" 
            Visibility="{Binding IsCheckBoxVisible, Mode=TwoWay, Converter={StaticResource BooleanToVisibilityConverter}, UpdateSourceTrigger=PropertyChanged}" > 
          </CheckBox> 
         <TextBlock Text="{Binding State_Name}"/> 
        </StackPanel> 
       </DataTemplate> 
       </ComboBox.ItemTemplate> 

      </ComboBox> 

    private void cbState_DropDownClosed(object sender, object e) 
     { 
      foreach (var item in (sender as ComboBox).Items) 
      { 
       (item as State).IsCheckBoxVisible = false; 
      } 
     } 

     private void cbState_DropDownOpened(object sender, object e) 
     { 
      foreach(var item in (sender as ComboBox).Items) 
      { 
       (item as State).IsCheckBoxVisible = true; 
      } 
     } 

конвертер класс

public class BooleanToVisibilityConverter : IValueConverter 
    { 
     public object Convert(object value, Type targetType, object parameter, string language) 
     { 
      var boolValue = System.Convert.ToBoolean(value); 

      return boolValue ? Visibility.Visible : Visibility.Collapsed; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, string language) 
     { 
      return ((Visibility)value == Visibility.Visible) ? true : false; 
      ; 
     } 
    } 

Модельный ряд. Реализовать INotifyPropertyChanged, чтобы отразить изменения в пользовательском интерфейсе (изменения флажок видимости)

public class State:INotifyPropertyChanged 
    { 
     public string State_Name { get; set; } 
     public object State_Id { get; set; } 
     bool isCheckBoxVisible; 
     public bool IsCheckBoxVisible 
     { 
      get { return isCheckBoxVisible; } 
      set 
      { 
       if (value != isCheckBoxVisible) 
       { 
        isCheckBoxVisible = value; 
        OnPropertyChanged("IsCheckBoxVisible"); 
       } 
      } 
     } 
     public State(string name,object id,bool visibility=false) 
     { 
      State_Name = name; 
      State_Id = id; 
      IsCheckBoxVisible = false; 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 

     public override string ToString() 
     { 
      return State_Name; 
     } 
     void OnPropertyChanged(string propertyName) 
     { 
      // the new Null-conditional Operators are thread-safe: 
      this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
     } 

    } 
Смежные вопросы