2016-06-29 145 views
0

WPFでコンボボックスの項目を非表示にする方法はありますか? 私のユーザコントロールには、チェックボックス項目がObservableCollectionにバインドされたListBoxと、コンボボックスを持つDataGridがあります。WPFでコンボボックスの項目を非表示にする方法

<ListBox x:Name="AvailableAttributes" Grid.Row="0" Grid.Column="2" SelectionMode="Single" > 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="{x:Type ListBoxItem}"> 
      <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=OneWay}"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 

    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}"/> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

... 

<DataGrid Name="datagrid" AutoGenerateColumns="False" > 
    <DataGrid.Columns> 
     <DataGridTextColumn Binding="{Binding Name}" /> 
      <DataGridComboBoxColumn 
       SelectedValueBinding="{Binding CBID}" 
       DisplayMemberPath="Name" 
       SelectedValuePath="ID"> 

       <DataGridComboBoxColumn.ElementStyle> 
        <Style TargetType="{x:Type ComboBox}"> 
         <Setter Property="ItemsSource" 
          Value="{Binding Path=CBItems, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /> 
        </Style> 
       </DataGridComboBoxColumn.ElementStyle> 
       <DataGridComboBoxColumn.EditingElementStyle> 
        <Style TargetType="{x:Type ComboBox}"> 
         <Setter Property="ItemsSource" 
          Value="{Binding Path=CBItems, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /> 
        </Style> 
       </DataGridComboBoxColumn.EditingElementStyle> 
      </DataGridComboBoxColumn> 
     </DataGrid.Columns> 
    </DataGrid> 

私は、コンボボックスの項目を管理するためにthis solutionを使用してプロパティを追加した「IsSelected」

public class GridItem 
{ 
    public string Name { get; set; } 
    public int CBID { get; set; } 
} 

public class CBItem 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public bool IsSelected { get; set; } 
} 

今私は、項目がコンボボックスに表示/非表示にする「IsSelected」プロパティを使用します。誰かが私にこれをどのように達成できるか教えてもらえますか?

答えて

1

非常にシンプル:あなたはIsSelectedの値を更新する可能性がある場合

<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}"> 
    <Setter Property="ItemsSource" 
     Value="{Binding Path=CBItems, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /> 
    <Setter Property="ItemContainerStyle"> 
     <Setter.Value> 
      <Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}"> 
       <Style.Triggers> 
        <DataTrigger Binding="{Binding IsSelected}" Value="False"> 
         <Setter Property="Visibility" Value="Collapsed" /> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </Setter.Value> 
    </Setter> 
</Style> 

:ちょうどComboBoxItemDataContextIsSelectedの値に応じてComboBoxItem.Visibilityを設定し、トリガーとコンボボックスの項目にスタイルを与えますComboBoxがグリッドに読み込まれた後、これらの項目のいずれかでimplement INotifyPropertyChangedCBItemに設定すると、UIに変更が反映されます。

+0

ありがとうございます!これは素晴らしいです:) –

関連する問題