2011-01-07 6 views
4

私が持っている場合は、その選択されたとき、私はその視覚的な状態を変更するDataTemplateでユーザーコントロールを伝えることができますどのようにカスタムユーザーコントロールが含まれている基本的なItemTemplateを持っているWPF ListBoxListBoxにありますか?WPFはDataTemplateをの視覚的な状態を変更

おかげであなたはあなたがIsSelected財産でトリガするListBoxItemのスタイルを設定することができます

答えて

7

与えることができます任意の助けのためにたくさん。ここでは例です:

、その後、あなたはこのようにそれを使用します。

<ListBox ItemContainerStyle="{StaticResource yourListBoxItemStyle}"> 

または直接ListBox自体に:

<ListBox.ItemContainerStyle> 
    <Style TargetType=”ListBoxItem”> 
     ... 
    </Style> 
</ListBox.ItemContainerStyle> 

編集:

ここには、ItemTemplateItemContainerStyleの両方を含む完全な例があり、選択した項目の上に半不透明なレイヤーを配置しています。

<Grid> 
    <Grid.Resources> 
     <x:Array Type="sys:String" x:Key="sampleData"> 
      <sys:String>Red</sys:String> 
      <sys:String>Green</sys:String> 
      <sys:String>Blue</sys:String> 
     </x:Array> 
     <DataTemplate x:Key="listBoxItem"> 
      <Rectangle Fill="{Binding}" Width="100" Height="100"/> 
     </DataTemplate> 
     <Style TargetType="ListBoxItem" x:Key="listBoxItemStyle"> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="ListBoxItem"> 
         <Grid> 
          <ContentPresenter /> 
          <Rectangle x:Name="Rectangle" Fill="Black" Opacity="0"/> 
         </Grid> 
         <ControlTemplate.Triggers> 
          <Trigger Property="IsSelected" Value="true"> 
           <Setter TargetName="Rectangle" Property="Opacity" 
            Value="0.5"/> 
          </Trigger> 
         </ControlTemplate.Triggers> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Grid.Resources> 
    <ListBox 
     ItemsSource="{StaticResource sampleData}" 
     ItemTemplate="{StaticResource listBoxItem}" 
     ItemContainerStyle="{StaticResource listBoxItemStyle}" 
     /> 
</Grid> 

編集

コメントした後、ここでは「統一」テンプレートを使用したバージョンは次のとおりです。

<Style TargetType="ListBoxItem" x:Key="listBoxItemStyle"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="ListBoxItem"> 
       <Grid> 
        <Rectangle Name="Rectangle" Fill="{Binding}" Width="100" Height="100" Opacity="1"/> 
       </Grid> 
       <ControlTemplate.Triggers> 
        <Trigger Property="IsSelected" Value="true"> 
         <Setter TargetName="Rectangle" Property="Opacity" 
          Value="0.5"/> 
        </Trigger> 
       </ControlTemplate.Triggers> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 
+0

ので、あなたがすべてでItemTemplateには使用しないと言っていますか? – Mark

+0

いいえ、あなたの 'ItemTemplate'を使い続けてください。この例の 'ControlTemplate'の' ContentPresenter'は 'ItemTemplate'を"拡張 "します。 –

+0

大丈夫ですが、itemcontainerテンプレートからコントロールにアクセスできないため、DataTemplate内のコントロール(あなたの場合はRectangleクラス)のプロパティを変更したい場合は、これがどのように動作するのかわかりません。 – Mark

関連する問題