2016-10-18 4 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> 

것은 내가이 버튼을 클릭하면 내 뷰 모델에 바인딩 된 목록 상자에있는 SelectedItem을 알고 싶어한다는 것입니다 :처럼는 다음과 같이 보인다. 항목을 먼저 선택하지 않으면이 선택 항목이 트리거되지 않습니다.

어떤 아이디어?

+0

CommandParameter = "{selectedItem가 바인딩, RelativeSource = {RelativeSource 모드 = FindAncestor, AncestorType : 여기

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

전체 작업 예입니다 = lists : MyControl} "가 작동하지 않습니까? –

+0

목록 상자에서 항목을 선택한 경우에만 작동합니다. 여기서는 그렇지 않습니다. –

+0

선택한 항목이 Null 일 때 검색 할 수 없다는 것을 의미합니까? –

답변

3

당신은 트리거로에 isSelected을 강제해야

<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>