【问题标题】:event handler + formatting multiple buttons - WPF事件处理程序 + 格式化多个按钮 - WPF
【发布时间】:2016-06-17 08:42:59
【问题描述】:

实际上,我有两个问题想要解决并整合到我的 wpf 应用程序中。

我有多个具有特定布局的按钮。

<Window.Resources>
    <Style x:Key="greenButton" TargetType="Button">
        <Setter Property="Background" Value="LightGreen" />
        <Setter Property="FontSize" Value="20"/>
        <Setter Property="BorderThickness" Value="1"/>
     </Style>
     ...        
</Window.Resources>   

好的,好的,这是我的按钮:

<Button x:Name="btn100" Grid.Column="0" Grid.Row="2" Style="{StaticResource greenButton}">100</Button>
<Button x:Name="btn101" Grid.Column="0" Grid.Row="3" Style="{StaticResource greenButton}">101</Button>
<Button x:Name="btn102" Grid.Column="0" Grid.Row="4" Style="{StaticResource greenButton}">102</Button>

然后,在单击按钮后,我想触发一个方法,该方法需要按钮的标题

    private void btn100_Click(object sender, RoutedEventArgs e)
    {
        name = (sender as Button).Content.ToString();
        doMethod(name);
    }

好的。但是我有这么多按钮,所以我想将它们与同一个单击事件处理程序结合在一起。我试过这个:

<StackPanel Button.Click="button_Click" Grid.RowSpan="20">
     <Button Grid.Column="0" Grid.Row="0" FontWeight="Bold" BorderBrush="Black" Style="{StaticResource greenButton}">LT 1</Button>
     <Button x:Name="btn100" Grid.Column="0" Grid.Row="2" Style="{StaticResource greenButton}">100</Button>
     <Button x:Name="btn101" Grid.Column="0" Grid.Row="3" Style="{StaticResource greenButton}">101</Button>
     <Button x:Name="btn102" Grid.Column="0" Grid.Row="4" Style="{StaticResource greenButton}">102</Button>
 </StackPanel>

我的 c# 代码现在是:

    private void button_Click(object sender, RoutedEventArgs e)
    {
        name= (sender as Button).Content.ToString();
        doMethod(name);
    }

现在我遇到了两个问题:

  1. 行对齐不适用于我的按钮。使用堆栈面板,它们现在比我在网格中定义的行更大/更高
  2. 我不知道按钮名称。它始终为空

谢谢提前帮助。

编辑: 没有In WPF can I attach the same click handler to multiple buttons at once like I can in Javascript/Jquery? 的重复我的解决方案是基于这篇文章,但我有问题更进一步(布局+传输变量)

【问题讨论】:

标签: c# wpf event-handling stackpanel


【解决方案1】:

当您将 Button.Click 处理程序分配给 StackPanel 时,处理程序方法的 sender 参数不是 Button,因此 (sender as Button) 返回 null。

您可以改写(e.OriginalSource as Button),通过在您的样式中通过EventSetter 将Click 处理程序分配给所有按钮可能更简单:

<Style x:Key="greenButton" TargetType="Button">
    ...
    <EventSetter Event="Click" Handler="button_Click"/>
</Style>

【讨论】:

  • 我删除了 stackpanel 并实施了你的建议,现在......它工作了 :) 非常感谢
【解决方案2】:

我认为,在这种情况下,发件人是 StackPanel。尝试使用:

string name = (e.OriginalSource as Button)?.Content.ToString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多