【问题标题】:Retrieving Selected Items from Checked List Box?从选中的列表框中检索选定的项目?
【发布时间】:2015-06-24 00:52:18
【问题描述】:

我已经实现了一个选中的列表框(或者更确切地说,尝试实现一个选中的列表框),它运行得很好。我已经能够使用目录中的文件列表填充它(这是我需要的),但是当我选择项目,然后尝试检查 .SelectedItems 属性时,列表中没有任何内容。

这是 XAML:

<ListBox x:Name="lbxSourceFiles" x:FieldModifier="private" SelectionMode="Multiple" Grid.Column="1" Grid.Row="2">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBoxItem IsSelected="{Binding IsChecked}">
                <CheckBox Content="{Binding Name}" Tag="{Binding FullName
            </ListBoxItem>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这就是我填充它的方式:

DirectoryInfo DI = new DirectoryInfo("Trivia Source Files");
this.lbxSourceFiles.ItemsSource = new ObservableCollection<FileInfo>( DI.GetFiles( "*.xls" ) );

很明显我在这里做错了,我到处都看到过关于如何创建这些东西的帖子,但我不知道如何让它在实际选择项目时起作用。

请告诉我我在这里做错了什么。

【问题讨论】:

    标签: c# wpf xaml checkboxlist checkedlistbox


    【解决方案1】:

    您的 DataTemplate 错误。您创建另一个 ListBoxItem,因此简化的可视化树看起来像这样:

    +- ListBox
    |  +- ListBoxItem
    |  |  +- ListBoxItem
    |  |     +- CheckBox
    |  +- ListBoxItem
    |  |  +- ListBoxItem
    |  |     +- CheckBox
    |  +- ListBoxItem
    |  |  +- ListBoxItem
    |  |     +- CheckBox
    

    只需从 DataTemplate 中删除 ListBoxItem 并在 CheckBox 中设置 Binding,您可以在其中找到正确的 ListBoxItem

    <DataTemplate>
        <CheckBox Content="{Binding Name}"
            IsChecked="{Binding 
                RelativeSource={RelativeSource 
                    Mode=FindAncestor, 
                    AncestorType={x:Type ListBoxItem}},
                Path=IsSelected,
                Mode=TwoWay}"
        Tag="{Binding FullName}" />
    </DataTemplate>
    

    【讨论】:

    • 完美。非常感谢。
    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多