2016-10-18 17 views
0

リストボックス内の各要素のスタイルを記述するItemContainerStyleのリストボックスがあります。このような何か次のようになります。Listbox.ItemContainer選択項目のスタイル

<ListBox.ItemContainerStyle> 
    <Style TargetType="ListBoxItem" BasedOn="{StaticResource MyStyle}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate> 
        <Border BorderThickness="0,0,0,1" BorderBrush="#1f000000" Padding="16 8"> 
         <Button Command={Binding MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=lists:MyControl}}}" /> 
        </Border> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</ListBox.ItemContainerStyle> 

を事は、私は、このボタンをクリックしたときに、私は私のViewModelにバインドされているリストボックスでSelectedItemを知りたい、ということです。最初に項目を選択しない限り、この選択はトリガーされません。

すべてのアイデア?

+0

CommandParameter = "{バインディングのSelectedItem、RelativeSource = {RelativeSourceモード= FindAncestor、AncestorType = lists:MyControl} "は機能しませんか? –

+0

リストボックスで項目が選択されている場合にのみ機能しますが、ここでは該当しません。 –

+0

選択したアイテムがNullであることを検出できないことを意味しますか? –

答えて

3

あなたが引き金とIsSelectedを強制する必要があります。ここでは

<Style.Triggers> 
     <Trigger Property="IsKeyboardFocusWithin" Value="True"> 
       <Setter Property="IsSelected" Value="True"/> 
     </Trigger> 
</Style.Triggers> 

はフル実施例である:

<ListBox x:Name="ListBox" ItemsSource="{Binding SomeList}" SelectedItem="{Binding SelectedListElement, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" > 
    <ListBox.ItemContainerStyle> 
      <Style TargetType="ListBoxItem" > 
       <Style.Triggers> 
        <Trigger Property="IsKeyboardFocusWithin" Value="True"> 
         <Setter Property="IsSelected" Value="True"/> 
        </Trigger> 
       </Style.Triggers> 
       <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate> 
         <Border BorderThickness="0,0,0,1" BorderBrush="#1f000000" Padding="16 8"> 
           <Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}}, 
           Path=DataContext.Run}" CommandParameter="{Binding}" Height="30" Width="100"/> 
         </Border> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox>