2012-07-31 99 views
3

對不起,模糊的標題,我不能想出一個很好的方式來總結正在發生的事情。ListSelect SelectionMode = Extended

我有一個綁定的WPF列表框:

<UserControl.Resources> 
    <DataTemplate DataType="{x:Type local:MyBoundObject}"> 
     <TextBlock Text="{Binding Label}" /> 
    </DataTemplate> 
</UserControl.Resources> 

<ListBox ItemsSource="{Binding SomeSource}" SelectionMode="Extended"> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="{x:Type ListBoxItem}"> 
      <Setter Property="IsSelected Value="{Binding Path=IsSelected, Mode=TwoWay}"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 

我只想選擇的項目進行操作。我通過迭代所有項目的列表並檢查每個對象來查看它是否設置了IsSelected屬性。

這個工作除了當我有很多項目在列表(足夠,所以他們都不可見),我按CTRL-A選擇所有項目。當我這樣做時,所有可見項都將其IsSelected屬性設置爲true,其餘所有項都保留爲false。只要向下滾動,其他項目就會進入視圖,然後將其IsSelected屬性設置爲true。

有沒有什麼辦法可以解決這個問題,以便在按下CTRL-A時每個對象的IsSelected屬性都設置爲true?

回答

4

嘗試集

ScrollViewer.CanContentScroll="False" 

在ListBox上,它應該修復ctrl + a的問題。

+0

這工作!謝謝! – ConditionRacer 2012-08-24 18:31:17

1

如果你想獲得所有選定的項目,你可以使用selectedItems屬性從Control。您不需要將IsSelected屬性添加到您的對象。

檢查下面的例子。

XAML文件:

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="30" /> 
     <RowDefinition Height="*" /> 
    </Grid.RowDefinitions> 

    <StackPanel Orientation="Horizontal"> 
     <Button Content="Selected items" Click="Button_Click" /> 
     <Button Content="Num of IsSelected" Click="Button_Click_1" /> 
    </StackPanel> 

    <ListBox Name="lbData" SelectionMode="Extended" Grid.Row="1"> 
     <ListBox.ItemContainerStyle> 
      <Style TargetType="{x:Type ListBoxItem}"> 
       <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/> 
      </Style> 
     </ListBox.ItemContainerStyle> 
    </ListBox> 
</Grid> 

代碼隱藏文件:

using System.Collections.Generic; 
using System.Windows; 
using System.Windows.Documents; 

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

      List<MyBoundObject> _source = new List<MyBoundObject>(); 
      for (int i = 0; i < 100000; i++) 
      { 
       _source.Add(new MyBoundObject { Label = "label " + i }); 
      } 
      lbData.ItemsSource = _source; 
     } 

     private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      MessageBox.Show(lbData.SelectedItems.Count.ToString()); 
     } 

     private void Button_Click_1(object sender, RoutedEventArgs e) 
     { 
      int num = 0; 
      foreach (MyBoundObject item in lbData.Items) 
      { 
       if (item.IsSelected) num++; 
      } 

      MessageBox.Show(num.ToString()); 
     } 
    } 

    public class MyBoundObject 
    { 
     public string Label { get; set; } 
     public bool IsSelected { get; set; } 
    } 
} 
相關問題