【问题标题】:ListBox with Button in ItemTemplate should do Select on ButtonClick also在 ItemTemplate 中带有按钮的 ListBox 也应该在按钮单击时选择
【发布时间】:2015-06-14 09:51:56
【问题描述】:

我有一个带有 ItemTemplate 的 ListBox。 在 ItemTemplate 中,我有一个 Button 和一个 TextBlock。

<Window x:Class="ListBoxItemWithToggleButton.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">
<Grid>
    <ListBox ItemsSource="{Binding ListItems}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Button Width="16" Height="16" Content="C" Padding="0" Margin="0,0,5,0"></Button>
                    <TextBlock Text="{Binding Path=Name}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

如果我点击 TextBlock 上的 ListBoxItem,ListItem 也会被选中, 但是如果我点击 Button 则不会选择 ListBoxItem。

如何在每次单击按钮时同时选择 Buttonclick 和 ListBoxItem?

【问题讨论】:

    标签: .net wpf


    【解决方案1】:

    您不需要选择 ListViewItem,您可以从 Button 的 DataContext 中获取您的数据对象,并且您不需要其他行的数据,因为您想要一个单一的选择。

    在事件处理程序中: var data = (sender as FrameworkElement).DataContext as MyData;

    (顺便说一句,你需要选择吗?如果不使用 ItemsControl)

    要使 ListViewItem 在单击按钮时自行选择,您可以像这样使用 ItemContainerStyle:

    <ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}">
        <Setter Property="IsSelected"
                Value="{Binding RelativeSource={RelativeSource Self}, Path=IsKeyboardFocusWithin, Mode=OneWay}" />
    </Style>
    

    【讨论】:

    • 我希望 ListBoxItem 为用户选择视觉问题(用户报告错误:“我点击了这个,但它没有被选中”)。你用多选尝试过你的答案吗 - 我无法让它工作!
    • 您是否将 ListViewItem 更改为 ListBoxItem?
    • 是的,我确实将所有 ListView 都更改为 ListBox。
    • 嗯...我会调查的。给我一些时间。
    • 你能重现吗?
    【解决方案2】:

    您可以尝试使用 OnPreviewButtonClick:

     <ListBox.ItemContainerStyle>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <EventSetter Event="PreviewMouseDown"
                                     Handler="ItemOnPreviewMouseDown" />
                    </Style>
                </ListBox.ItemContainerStyle>
    

    在后面的代码中:

    private void ItemOnPreviewMouseDown(
                object sender, MouseButtonEventArgs e)
            {
                ((ListBoxItem) sender).IsSelected = !((ListBoxItem) sender).IsSelected;
            }
    

    有关此问题的答案请查看here

    【讨论】:

    • 但这只会选择ListBoxItem!再次单击也应取消选择。如果单击文本框,它的行为应该完全一样!
    • 嘿,我编辑了代码。 (第二部分)根据要求。
    • 是的,但请尝试使用 SelectionMode="Extended" - 它无法按预期工作,导致您的代码每次都切换。
    • 我以为你想切换,你想达到什么目的?
    • 我只想要 ListBoxItem 的“正常”行为,但也可以获得按钮点击。正如您在问题中所读到的,如果我单击 TextBox,则行为正常,但如果我单击按钮,则选择不会像“正常”(shift 和 ctrl 选择)那样改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2014-08-30
    • 1970-01-01
    相关资源
    最近更新 更多