在WPF项目中,我有ListBox
,ItemsSource
绑定了一组项目。我在DataTemplate
的{{1}}中使用ItemTemplate
来表示这些项的UI。
我想要发生的是,当用户点击DataTemplate的任何部分以获取绑定项时,ListBox
将设置为ListBox.SelectedItem
它的项目是。然后将应用选定的DataTemplate
。从下面的示例代码中可以看到,单击Label很好。但是,Style
和Button
等控件的行为并不理想,其他人也毫不怀疑。我怀疑它与焦点有关。
我怎么能实现这个目标?
XAML:
TextBox
代码背后:
<Window x:Class="ListViewSelectionOverride.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ListViewSelectionOverride"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox ItemsSource="{Binding}">
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="OverridesDefaultStyle" Value="true" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border
Name="Border"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="BorderBrush" Value="Blue"/>
<Setter TargetName="Border" Property="BorderThickness" Value="1"/>
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border x:Name="itemTemplateBorder">
<Grid >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Margin="3,3,3,0" Grid.Row="0" Content="Label"/>
<Button Margin="3,3,3,0" Grid.Row="1" Content="Button"/>
<TextBox Margin="3,3,3,0" Grid.Row="2" Text="TextBox"/>
<CheckBox Margin="3,3,3,0" Grid.Row="3" Content="CheckBox"/>
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
答案 0 :(得分:1)
您可以处理模板中PreviewMouseLeftButtonDown
元素的Border
事件,并明确选择相应的项目:
private void Border_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Border border = sender as Border;
lvv.SelectedItem = border.DataContext;
}
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="Border" Padding="2" SnapsToDevicePixels="true"
PreviewMouseLeftButtonDown="Border_PreviewMouseLeftButtonDown">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Border" Property="BorderBrush" Value="Blue"/>
<Setter TargetName="Border" Property="BorderThickness" Value="1"/>
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>