我的应用程序中有 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/