C# 按钮样式的列表框没有';好像不行

C# 按钮样式的列表框没有';好像不行,c#,wpf,xaml,listbox,C#,Wpf,Xaml,Listbox,我的应用程序中有两个使用 <Window.Resources> <ItemsPanelTemplate x:Key="WrapPanelTemplate"> <WrapPanel Width="290"/> </ItemsPanelTemplate> <DataTemplate x:Key="ButtonItemTemplate"> <Button Content="{Bin

我的应用程序中有两个使用

<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绑定到视图模型上的属性,但每当我选择一个新项时,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>


谢谢

问题在于
按钮
吞下了鼠标点击,因此
列表框
中的
列表框项目
从未接收到它,因此它从未被选中。如果您想在单击
按钮时选择项目,可以尝试使用
切换按钮
,并将
IsChecked
绑定到
IsSelected

<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>

您也可以通过一点代码隐藏或附加行为来实现这一点

按钮模板

<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;
}
private void TemplateButton\u单击(对象发送者,路由目标)
{
按钮clickedButton=发送者为按钮;
ListBoxItem ListBoxItem=GetVisualParent(单击按钮);
如果(listBoxItem!=null)
{
listBoxItem.IsSelected=true;
}
}
公共静态T GetVisualParent(对象子对象),其中T:Visual
{
DependencyObject子对象=作为DependencyObject的子对象;
//迭代遍历可视化树
while((child!=null)&&&!(child是T))
{
child=visualtreeheloper.GetParent(child);
}
返回子对象作为T;
}

谢谢您的回答。我明天上班时得去看看。