c# - 列表框 SelectionChanged 不能在其 ItemTemplate 中使用 Button

标签 c# wpf listbox selectionchanged

当我在列表框中选择项目时,下面的代码不起作用,您知道为什么吗?

<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 看起来像这样

 <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

您可以将事件处理程序设置为按钮的点击事件。

   <Button Height="90" Width="150" Click="myClickEventHandler"/>  

无论如何,我建议您使用 MVVM ,而不是代码隐藏事件处理程序。

你可以设置一个命令,当按钮被点击时触发,例如发送按钮内容的命令

  <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>

View 模型

DoSomething = new DelegateCommand<object>(content=> 
{
    // Do whatever you want 

});

如果您不熟悉 MVVM,学习它需要一些时间,但绝对值得:)

关于c# - 列表框 SelectionChanged 不能在其 ItemTemplate 中使用 Button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18957558/

相关文章:

c# - IControllerFactory 与 IControllerActivator asp.net core

java - 在 Java 中,通过 TCP 套接字从 C# 应用程序接收音频数据流并在接收时播放流媒体

wpf - 在 WPF 中使用命令

c# - CefSharp WPF 错误

c# - WPF中的ComboBox模板问题

silverlight - Silverlight如何在数据模板中使用按钮时提升列表框的选定项目

c# 可以将登录凭据(非显式)与 wsmanconnectioninfo 一起使用吗?

用户定义类中的 C# UpdateListBox 方法声明

c# - 列表框selectedItem问题

c# - 使用 .NET 4.6 验证 xml 时出现 NullReferenceException