c# - 按钮样式的列表框似乎不起作用

标签 c# wpf xaml listbox

我的应用程序中有 2 个列表框使用

<Window.Resources>
    <ItemsPanelTemplate x:Key="WrapPanelTemplate">
        <WrapPanel Width="290"/>
    </ItemsPanelTemplate>
    <DataTemplate x:Key="ButtonItemTemplate">
        <Button Content="{Binding Path=Name}" Width="120" Margin="3,2,3,2" />
    </DataTemplate>
</Window.Resources>

一切看起来都很棒,但是当我尝试单击它们时,它们没有选择新项目。我已将 SelectedItem 绑定(bind)到 View 模型上的属性,但每当我选择新项目时, set 方法都不会发生。我有一个常规列表框,以相同的方式连接并且可以工作。这是自定义列表框的实现:

<ListBox Height="284" HorizontalAlignment="Left" x:Name="faveProgramsButtons" 
    ItemsSource="{Binding Path=FavoriteAppList}" 
    SelectedItem="{Binding Path=FavoriteAppList_SelectedApp}" VerticalAlignment="Top" 
    Width="281" ItemsPanel="{StaticResource WrapPanelTemplate}"
    ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
    ItemTemplate="{StaticResource ButtonItemTemplate}">
</ListBox>

谢谢!

最佳答案

问题是 Button 吞没了鼠标点击,因此 ListBox 中的 ListBoxItem 永远不会收到它,因此永远不会选择它。如果您希望在单击 Button 时能够选择项目,您可以尝试使用 ToggleButton 并将 IsChecked 绑定(bind)到 已选中

<DataTemplate x:Key="ButtonItemTemplate">
    <ToggleButton Content="{Binding Path=Name}" Width="120" Margin="3,2,3,2" 
                  IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                      Path=IsSelected,
                                      Mode=TwoWay}"/>
</DataTemplate>

您还可以通过一些隐藏代码或附加行为来实现此目的。

ButtonItemTemplate

<DataTemplate x:Key="ButtonItemTemplate">
    <Button Content="{Binding Path=Name}" Width="120" Margin="3,2,3,2"
            Click="TemplateButton_Click"/>
</DataTemplate>

代码隐藏

private void TemplateButton_Click(object sender, RoutedEventArgs e)
{
    Button clickedButton = sender as Button;
    ListBoxItem listBoxItem = GetVisualParent<ListBoxItem>(clickedButton);
    if (listBoxItem != null)
    {
        listBoxItem.IsSelected = true;
    }
}

public static T GetVisualParent<T>(object childObject) where T : Visual
{
    DependencyObject child = childObject as DependencyObject;
    // iteratively traverse the visual tree
    while ((child != null) && !(child is T))
    {
        child = VisualTreeHelper.GetParent(child);
    }
    return child as T;
}

关于c# - 按钮样式的列表框似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6904264/

相关文章:

c# - 获取 ComboBox 的 SelectedItem (MVVM)

c# - Xamarin XAML 表单的 Stack Layout 布局噩梦

wpf - 如何在 XAML 中获取 DynamicResource 的属性?

c# - GUI 启动时的控制台 "Hangs"

wpf - DataTemplate 中的 RelativeSource 适用于 TabControl 但不适用于 TabItem

.net - 允许非开发人员定义 Workflow Foundation 4 流程的解决方案

C#调整大小时锚定控件 "shakes"

c# - 无法确定某个 UITestControl 是否存在于我的网络应用程序中

c# - 为了实现最佳的逐行处理,blob 内容应该绑定(bind)到哪个 C# 数据结构?

c# - 使用 LINQ 的 IQueryable 左外连接的扩展方法