从项目模板控件事件中获取ListBoxItem

本文关键字:获取 ListBoxItem 事件 控件 项目 | 更新日期: 2023-09-27 18:05:15

在下面的WPF XAML代码中,如果我在模板化按钮的SelectTaskItemClick事件中,我如何获得当前选中的ListBoxItem ItemSource对象?

    <!-- ListBox ITEMS -->
    <TaskDash:ListBoxWithAddRemove x:Name="listBoxItems" Grid.Row="1" Grid.Column="3" Grid.RowSpan="3"
        ItemsSource="{Binding}">
        <!--ItemsSource="{Binding}" DisplayMemberPath="Description">-->
        <Style TargetType="ListBoxItem">
            <Setter Property="IsSelected" Value="{Binding Path=Selected}"/>
        </Style>
        <TaskDash:ListBoxWithAddRemove.ItemTemplate>
            <DataTemplate>
                <DockPanel>
                    <Button DockPanel.Dock="Left" Click="SelectTaskItemClick">SELECT</Button>
                    <TextBox DockPanel.Dock="Left" Name="EditableDescription" Text="{Binding Description}" Height="25" Width="100" />
                    <Button DockPanel.Dock="Left" Click="EditTaskItemClick">EDIT</Button>
                </DockPanel>
            </DataTemplate>
        </TaskDash:ListBoxWithAddRemove.ItemTemplate>
    </TaskDash:ListBoxWithAddRemove>

如果我尝试获取Parent或templatepparent,它会给我ContentPresenter或Style或类似的东西。

    private void SelectTaskItemClick(object sender, RoutedEventArgs e)
    {
        Button taskItemButton = (Button) e.OriginalSource;
        ContentPresenter taskItem = (ContentPresenter) taskItemButton.TemplatedParent;
        taskItem = (ContentPresenter)taskItemButton.TemplatedParent;
        Style taskItem2 = taskItem.TemplatedParent;
        taskItem2 = taskItem.TemplatedParent;
        DependencyObject taskItem3 = taskItem2.Parent;
        //DependencyObject taskItem3 = taskItem2.TemplatedParent;
        //TaskItem taskItemObj = taskItem2;
    }

在上面的代码中,我猜它是从App.XAML中定义自定义ListBoxWithAddRemove控件的地方抓取的。我如何遍历实际表单的XAML而不是[上面显示的第一个代码]?

<Style x:Key="{x:Type TaskDash:ListBoxWithAddRemove}" TargetType="{x:Type     TaskDash:ListBoxWithAddRemove}">
            <Setter Property="Margin" Value="3" />
            <Setter Property="SnapsToDevicePixels" Value="True"/>
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="MinWidth" Value="120"/>
            <Setter Property="MinHeight" Value="20"/>
            <Setter Property="AllowDrop" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TaskDash:ListBoxWithAddRemove}">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="25" />
                                <RowDefinition Height="*" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="*" />
                            </Grid.ColumnDefinitions>
                            <Button Grid.Column="0" Grid.Row="0" 
                                    Click="DeleteControlClick">Delete</Button>
                            <Button Grid.Column="1" Grid.Row="0" 
                                    Click="AddControlClick">Add</Button>
                            <Border 
                                Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2"
                                  Name="Border" 
                                  Background="{StaticResource WindowBackgroundBrush}"
                                  BorderBrush="{StaticResource SolidBorderBrush}"
                                  BorderThickness="1"
                                  CornerRadius="2">
                                <ScrollViewer 
                                    Margin="0"
                                    Focusable="false">
                                    <StackPanel Margin="0" IsItemsHost="True" />
                                </ScrollViewer>
                            </Border>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

从项目模板控件事件中获取ListBoxItem

您可以使用VisualTreeHelper沿着树走,如果您有正确类型的对象,则停止,例如

private void SelectTaskItemClick(object sender, RoutedEventArgs e)
{
    var b = sender as Button;
    DependencyObject item = b;
    while (item is ListBoxItem == false)
    {
        item = VisualTreeHelper.GetParent(item);
    }
    var lbi = (ListBoxItem)item;
    //...
}

(如果你只想选择可以(并且应该)通过已建立的绑定完成的项,例如)

private void SelectTaskItemClick(object sender, RoutedEventArgs e)
{
    // The DataContext should be an item of your class that should
    // have a Selected property as you bind to it in a style.
    var data = (sender as FrameworkElement).DataContext as MyClass;
    data.Selected = true;
}

<Style TargetType="ListBoxItem">
    <Setter Property="IsSelected" Value="{Binding Path=Selected}"/>
</Style>

按照预期的方式工作,您应该能够循环遍历用作列表框ItemsSource的DataContext中的项,并检查每个项的Selected属性以查找当前被选中的项。从ListBox中确定选中项的更典型的方法是使用ListBox。其中listBox是指向所讨论的listBox的变量。或者,您可以通过SelectTaskItemClick方法的sender参数访问它。您可以尝试的另一种方法是遍历可视化树的helper方法,例如在the Coding block和the Code Project - LINQ to visual tree中描述的方法。