2012-07-31 54 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; } 
    } 
} 
相关问题