gpt4 book ai didi

c# - 事件处理程序 + 格式化多个按钮 - WPF

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:46 25 4
gpt4 key购买 nike

实际上,我有两个问题想解决并在我的 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? 没有重复项我的解决方案基于这篇文章,但我在更进一步时遇到了问题(布局 + 传输变量)

最佳答案

当您将 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>

关于c# - 事件处理程序 + 格式化多个按钮 - WPF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37876936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com