2014-11-14 1 views
1

ListBox의 인덱스에 액세스하여 해당 인덱스를 증가시키고 싶습니다. ItemContainerGenerator을 사용하려고했지만 ListBox 또는 ItemsControl으로 항목을 캐스팅 할 때 null을 반환합니다.WPF에서 다른 ListBox 내부에서 ListBox의 인덱스를 어떻게 증가시킬 수 있습니까?

코드 또는 뷰 모델에서 색인을 증가시키고 싶습니다. 여기

내 템플릿의 기본 구조입니다

<Window x:Class="WpfApplication12.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
     <Style x:Key="MyListStyle" TargetType="{x:Type ListBox}"> 

      <Setter Property="BorderThickness" Value="0"></Setter> 
      <Setter Property="SelectedIndex" Value="0"></Setter> 

      <Setter Property="ItemsPanel"> 
       <Setter.Value> 
        <ItemsPanelTemplate> 
         <VirtualizingStackPanel Orientation="Horizontal"> 

         </VirtualizingStackPanel> 
        </ItemsPanelTemplate > 
       </Setter.Value> 
      </Setter> 
      <Setter Property="ItemContainerStyle"> 
       <Setter.Value> 
        <Style TargetType="{x:Type ListBoxItem}" > 
         <Setter Property="Visibility" Value="Collapsed"></Setter> 

         <!--<Setter Property="Margin" Value="2" />--> 
         <Setter Property="Template"> 

          <Setter.Value> 
           <ControlTemplate TargetType="{x:Type ListBoxItem}"> 
            <ListBox Name="InnerList" ItemsSource="{Binding}" ></ListBox> 
           </ControlTemplate> 
          </Setter.Value> 

         </Setter> 
         <Style.Triggers> 
          <Trigger Property="IsSelected" Value="true"> 
           <Setter Property="Visibility" Value="Visible"/> 
          </Trigger> 
         </Style.Triggers> 
        </Style> 
       </Setter.Value> 
      </Setter> 
     </Style> 
    </Window.Resources> 

    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition></RowDefinition> 
      <RowDefinition></RowDefinition> 
     </Grid.RowDefinitions> 

     <Button Grid.Row="1" Click="Button_Click">button</Button> 
     <ListBox Style="{StaticResource MyListStyle}" Name="ListItemsControl" VirtualizingPanel.IsVirtualizing="True" Grid.Row="0"></ListBox> 
    </Grid> 
</Window> 

Here is some code to load the list 


     public MainWindow() 
     { 
      InitializeComponent(); 

      CompositeCollection cc = new CompositeCollection(); 
      cc.Add(new List<int>() { 1, 2, 3, 4, 5 }); 
      cc.Add(new List<int>() { 6, 7, 8, 9, 10 }); 
      cc.Add(new List<int>() { 11, 12, 13, 14, 15 }); 
      ListItemsControl.ItemsSource = cc; 



     } 
+0

내부 'ListBox'는 실제로 다른 'ListBox'안에 있거나 단순히 다른 ListBox의 선택된 인덱스를 기반으로 하나의 'ListBox'를 증가 시키시겠습니까? –

+0

목록 상자로 채워진 목록 상자 목록 상자가 선택되었을 때 내부 목록 상자의 색인을 증가시킬 수 있기를 원합니다. – Bob

+0

MVVM 패턴 또는 코드 숨김을 사용하고 있습니까? –

답변

1

난 당신이 중단 점을 사용하고 (당신이 변수를 통해 원하는 경우 작은 돋보기 아이콘) 당신의 아이디어를 얻을 수 있도록 시각화를 통해 도보로 추천 이 코드가 어떻게 작동하는지. 귀하의 버튼 이벤트 핸들러에

장소이 : 주석

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    //var item = ListItemsControl.ItemContainerGenerator.ContainerFromIndex(1) as ListBoxItem; 
    //var innerListBox = VisualTreeHelper.GetChild(item, 0) as ListBox; 
    //innerListBox.SelectedIndex++; 

    // For every item in the ListItemsControl 
    for (int i = 0; i < ListItemsControl.Items.Count; i++) 
    { 
     // Get the item container for the specified index and cast it as ListBoxItem. 
     var item = ListItemsControl.ItemContainerGenerator.ContainerFromIndex(i) 
      as ListBoxItem; 
     // Then, get the first child of the ListBoxItem and cast it as a ListBox. 
     // Note that I'm making an assumption that it'll always be a ListBox, 
     // which is why you should perform some checks in a production case, 
     // to avoid exceptions. 
     var innerListBox = VisualTreeHelper.GetChild(item, 0) as ListBox; 
     // Lastly, I increment the index of this ListBox. 
     innerListBox.SelectedIndex++; 
    } 
} 

은 하나 개의 요소의 인덱스를 변경하는 방법입니다. 아래, 세 개의 내부 목록 상자의 색인을 증가시킵니다. 이것은 당신에게 그들에게 도착하는 방법에 대한 아이디어를 제공합니다, 그래서 거기에서 당신이 그것을 당신의 취향에 맞게 바꿀 수 있습니다. 당연히 null을 확인하기위한 코드를 추가하고 SelectedIndex 속성을 증가시키기 전에 올바른 유형을 확인하는 것이 좋지만 그다지 어렵지는 않습니다. (첫 번째 게시물 기준)

올드 답변 :

이것은 코드 숨김 예입니다. MVVM을 원하면 알려주세요. Binding ~ SelectedIndex 속성을 사용할 수도 있지만 INotifyPropertyChanged을 구현해야합니다.

enter image description here

XAML :

<Window x:Class="LB.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="219.965" Width="217.535"> 
    <StackPanel> 
     <ListBox x:Name="lbOuter" HorizontalContentAlignment="Stretch"> 
      <ListBox.Items> 
       <TextBlock>Outer Item #1</TextBlock> 
       <TextBlock>Outer Item #1</TextBlock> 
       <ListBox x:Name="lbInner" BorderBrush="Black" BorderThickness="1" Margin="5"> 
        <ListBox.Items> 
         <TextBlock>Inner Item #1</TextBlock> 
         <TextBlock>Inner Item #2</TextBlock> 
         <TextBlock>Inner Item #3</TextBlock> 
        </ListBox.Items> 
       </ListBox> 
       <TextBlock>Outer Item #3</TextBlock> 
       <TextBlock>Outer Item #4</TextBlock> 
      </ListBox.Items> 
     </ListBox> 
     <StackPanel Orientation="Horizontal"> 
      <Button Content="Increment Outer" Margin="5" Click="Button_Click"/> 
      <Button Content="Increment Inner" Margin="5" Click="Button_Click_1"/> 
     </StackPanel> 
    </StackPanel> 
</Window> 

코드 숨김 :

using System.Windows; 

namespace LB 
{ 
    public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      if (lbOuter.SelectedIndex < (lbOuter.Items.Count - 1)) 
      { 
       lbOuter.SelectedIndex++; 
      } 
      else 
      { 
       lbOuter.SelectedIndex = 0; 
      } 
     } 

     private void Button_Click_1(object sender, RoutedEventArgs e) 
     { 
      if (lbInner.SelectedIndex < (lbInner.Items.Count - 1)) 
      { 
       lbInner.SelectedIndex++; 
      } 
      else 
      { 
       lbInner.SelectedIndex = 0; 
      } 
     } 
    } 
} 

위의 코드 것입니다 실제로 루프를 선택. 따라서 끝까지 도달하면 인덱스 0으로 이동합니다. 기능을 원하지 않는다면 제거 할 수 있습니다.

+1

내 설정에서 CompositeCollection에 대한 데이터 템플릿을 사용하고 있습니다. 그리고 나가는 ListBox의 ItemsContainer에 대한 컨트롤 템플릿에 설정된 ListBox의 이름에 액세스 할 수 없습니다. – Bob

+0

@Bob 아, 나는 당신의 원래 지위에 근거한 것을 인식하지 못했습니다. –

+0

@BK 죄송합니다. 원래 게시물에서 명확하지 않고 내 설명을 업데이트 함을 깨달았습니다. – Bob

관련 문제