我自己在XAML中使用了ListBox(我的语言也是C#,我使用的是VS2010)。在这个ListBox中我有几个项目,我也有一个SelectionChanged事件。对我来说问题是该事件仅针对项目的一部分进行。
这张图片清楚地表明了我的想法:
在这种情况下,' n1'被选中,但为了选择不同的一个,我必须点击项目边缘周围的一个狭窄区域 - 我们现在可以看到n1周围的深蓝色区域。
有没有办法将此SelectionChanged应用于项目的不同部分?显然那里有文本输入,所以不是那个部分,但其余部分会很棒。
项目本身位于ListBox控件内,ListBox.Item模板中的数据模板如下:
<Thumb Name="myThumb" Template="{StaticResource NodeVisualTemplate}">
提到的静态资源如下:
<ControlTemplate x:Key="NodeVisualTemplate">
<Border BorderThickness="2" BorderBrush="LightBlue" Margin="2" CornerRadius="5,5,5,5">
<StackPanel>
<TextBlock Text="Test" Background="AntiqueWhite"/>
<TextBlock Text="{Binding Path=NodeText}" Background="Aqua"/>
<StackPanel Orientation="Horizontal">
<TextBox Text="Type here" MinWidth="50"/>
<Image Source="{StaticResource ImgFolder}" Margin="0,0,5,0" Width="32" Height="32"/>
</StackPanel>
</StackPanel>
</Border>
</ControlTemplate>
答案 0 :(得分:2)
当您点击其中的任何位置时,您可以处理PreviewMouseLeftButtonDown
容器的ListBoxItem
以选择它:
<ListBox x:Name="lb">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="lb_PreviewMouseLeftButtonDown" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Thumb Name="myThumb" Template="{StaticResource NodeVisualTemplate}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void lb_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ListBoxItem lbi = sender as ListBoxItem;
lb.SelectedItem = lbi.DataContext;
}
这应该按预期触发SelectionChanged
事件。