问题描述
我有一个带有项目数据模板的列表框.问题是仅通过单击项目上的任意位置来选择项目不起作用.我必须点击一个特定的子元素才能真正起作用.
我的项目有一个图像和一个文本块.如果我将鼠标悬停在图像或文本块上,我实际上会看到悬停效果.如果我将鼠标悬停在项目的任何空白"空间上,则没有悬停效果(当我点击那里时也没有选择).
示例图片:http://i33.tinypic.com/wvtleg.pngp>
如果我单击(或将鼠标悬停在)实际文本或图像上它可以正常工作,但是如果我将鼠标悬停在空白区域(我在它周围画了一条红线:))列表框没有响应.
如何让列表框悬停/单击以响应单击项目空间中的任意位置?
为了完整起见,这里是我的 Listbox + 模板:
正如 Quartermeister 指出的那样-您需要设置网格的背景-但您还需要在资源中设置以下样式,因为设置了 ListBoxItems 的 HorizontalContentAlignment默认为左.(仅在 ListBox 上设置是不够的)
<ListBox.Resources><Style TargetType="{x:Type ListBoxItem}"><Setter Property="HorizontalContentAlignment" Value="Stretch"/></风格></ListBox.Resources>
I have a listbox with a datatemplate for the items.The problem is that selecting an item doesn't work by just clicking anywhere on the item; I have to click on a specific sub-element for it to actually work.
My item has an image and a textblock.If I hover the mouse over the image or text-block, I actually see the hover-effect.If I hover the mouse over any of the 'empty' space of the item, no hover effect (and no selection when I click there).
Example image : http://i33.tinypic.com/wvtleg.png
If I click on (or hover over) the actual text or the image it works fine,but if i hover my mouse in the empty areas (I've drawn a red line around it :)) the listbox doesn't respond.
How do I get the listbox hovering / clicking to respond to clicking anywhere in the item's space ?
For completeness here is my Listbox + template:
<ListBox Grid.Row="1"
ItemsSource="{Binding Path=CreatableOutputWindows, Mode=OneWay}" Height="Auto"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Margin="8,8,8,8"
Name="listBox1" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="84"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Margin="5" BorderBrush="Black" BorderThickness="2">
<Image Source="{Binding Path=Image}" Stretch="Fill" Width="80" Height="50" />
</Border>
<StackPanel Grid.Column="1" Margin="5">
<StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold">
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
As Quartermeister pointed out - you need to set the Background of the Grid - but you also need to set the following style in your resources as ListBoxItems' HorizontalContentAlignment is set to Left by default. (It isn't enough to set it on the ListBox)
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.Resources>
这篇关于列表框数据模板 - 项目只能通过单击子元素来选择,而不仅仅是项目上的任何位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!