3

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

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

2 回答 2

2

SelectionChanged事件不会被触发,因为按钮是捕获鼠标点击的控件,而不是ListBox.

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

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

无论如何,我建议您使用MVVM,而不是 Code-Behind 事件处理程序。

您可以设置一个命令,该命令将在单击按钮时触发并将命令发送到按钮的内容,例如

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

视图模型

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

});

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

于 2013-09-23T11:23:25.107 回答
2

您可以在 ListBoxItem 上添加 PreviewMouseDown 事件处理程序:

    <ListBox ItemsSource="{Binding ListBoxItemsSource}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <EventSetter Event="PreviewMouseDown"
                             Handler="ItemOnPreviewMouseDown" />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>


    private void ItemOnPreviewMouseDown(
        object sender, MouseButtonEventArgs e)
    {
        ((ListBoxItem) sender).IsSelected = true;
    }
于 2017-02-15T12:28:27.087 回答