列表框SelectionChanged不适用于其ItemTemplate中的Button [英] Listbox SelectionChanged not working with Button in its ItemTemplate
问题描述
当我在列表框中选择项目时,以下代码不起作用,您碰巧知道为什么吗?
Code below does not work when I select item in listbox, do you happen to know why?
<ListBox BorderBrush="Transparent" Background="Transparent" Name="listbox" HorizontalAlignment="Center" VerticalAlignment="Center" ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionChanged="selection_changed">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Height="90" Width="150" Template="{StaticResource cbutton}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
模板cbutton看起来像这样
And template cbutton looks like this
<ControlTemplate x:Key="cbutton" TargetType="Button">
<Border CornerRadius="3" BorderThickness="3.5" BorderBrush="White">
<Border.Background>
<LinearGradientBrush EndPoint="1,1" StartPoint="0,0">
<GradientStop Color="DarkOrange" Offset="0.1"/>
<GradientStop Color="Orange" Offset="0.85"/>
</LinearGradientBrush>
</Border.Background>
<TextBlock FontWeight="ExtraBold" Foreground="White" TextAlignment="Center" TextWrapping="Wrap" FontSize="15" Text="{Binding name}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Border>
</ControlTemplate>
推荐答案
不会触发SelectionChanged
事件,因为按钮是捕获鼠标单击的控件,而不是ListBox
.
The SelectionChanged
event is not fired because the button is the control who captures the mouse click, not the ListBox
.
您可以将事件处理程序设置为按钮的click事件.
You can set your event handler to the button's click event instead.
<Button Height="90" Width="150" Click="myClickEventHandler"/>
无论如何,我建议您使用 MVVM 代替代码-在事件处理程序之后.
Regardless, I recommend you to use MVVM, instead of Code-Behind event handler.
您可以设置一个命令,在单击按钮时将触发该命令,并向该命令发送按钮的内容,例如
you could set a command which will fire when the button's click and send the command the button's content for example
<Button Name="myButton" Height="90" Width="150" Template="{StaticResource cbutton}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding DoSomething}" CommandParameter="{Binding ElementName=myButton, Path=Content}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
ViewModel
ViewModel
DoSomething = new DelegateCommand<object>(content=>
{
// Do whatever you want
});
如果您不熟悉MVVM,则需要花一些时间来学习它,但绝对值得:)
If your not familar with MVVM, it will take some time to learn it, but it is definetly worth it :)
这篇关于列表框SelectionChanged不适用于其ItemTemplate中的Button的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!