我有一个ListBoxItems的问题.我正在尝试使ListBoxItem中的所有控件也选择它,因此单击TextBox,Label等将选择ListBoxItem.到目前为止很简单.
我也在更改ListBoxItem模板以更改选择可视化,从突出显示背景到仅绘制边框.也很简单.
然而,这两者的结合似乎会导致MouseDown和PreviewMouseDown出现一些非常棘手的问题,特别是在我关于网格中标签的情况下,其中一个创建了一个由网格空间占据的“空白”.
使用snoop,我可以看到PreviewMouseDown事件在ListBox内的ScrollViewer处停止,而不是一直到ListBoxItem.
XAML:
<Window x:Class="ListBoxClickThroughTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Width="525" Height="350"> <Grid> <ListBox ItemsSource="{Binding Items}" SelectionMode="Single"> <ListBox.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Label Name="VerySuperLongLabel" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" Content="VerySuperLongLabel" Padding="0" /> <TextBox Name="TextBox1" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" HorizontalContentAlignment="Right" Text="TextBox1 Text" /> <Label Name="ShortLabel" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left" Content="ShortLabel" Padding="0" /> <TextBox Name="TextBox2" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" HorizontalContentAlignment="Right" Text="TextBox2 Text" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <EventSetter Event="PreviewMouseDown" Handler="ListBoxItem_PreviewMouseDown" /> <EventSetter Event="MouseDown" Handler="ListBoxItem_PreviewMouseDown" /> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Border x:Name="Bd" BorderThickness="1"> <ContentPresenter /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSelected" Value="true"> <Setter TargetName="Bd" Property="BorderBrush" Value="Gray" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ListBox.ItemContainerStyle> </ListBox> </Grid> </Window>
代码隐藏:
using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace ListBoxClickThroughTest { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { Items = new List<string>() { "1","2" }; InitializeComponent(); DataContext = this; } public List<string> Items { get; set; } private void ListBoxItem_PreviewMouseDown(object sender,MouseButtonEventArgs e) { var listBoxItem = (ListBoxItem)sender; listBoxItem.IsSelected = true; } } }
但是,如果我删除模板设置器,一切都很好.我缺少的模板中是否有一些魔法?我尝试将边框重命名为“Bd”,因为这是默认模板边框的名称,但没有运气.有任何想法吗?