gpt4 book ai didi

c# - 在运行时复制控制按钮

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

大家好。我使用一些 (WPF) 表单创建了一个应用程序。我在一个表格上有一个按钮。我想在运行时将此按钮复制到第二个窗体上,而不必再次创建它。

例如:我在表单 1 上有一个“X”按钮。在运行时,我在表单 2 上创建了这个按钮的副本,其所有属性值都与表单 1 上的原始按钮相同。

按钮:

<Button Content="Open Window" Click="ButtonClicked" Height="25"
HorizontalAlignment="Left" Margin="379,264,0,0" Name="button1"
VerticalAlignment="Top" Width="100" />

我是否有机会避免必须重现此代码?

最佳答案

您可以在 App.xaml 中为按钮定义自己的样式:

<Application x:Class="WpfButton.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style x:Key="myBtnStyle" TargetType="Button" >
<Setter Property="Content" Value="Open Window" />
<Setter Property="Height" Value="25" />
<Setter Property="Width" Value="100" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Margin" Value="379,264,0,0" />
<Setter Property="VerticalAlignment" Value="Top" />
<EventSetter Event="Click" Handler="myBtn_Click" />
</Style>
</Application.Resources>
</Application>

代码隐藏:

public partial class App : Application
{
public void myBtn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
// ...
}
}

当你想要将创建的早期样式分配给按钮时,你应该使用 StaticResource 和你的样式名称:

 <Button Style="{StaticResource myBtnStyle}" />

关于c# - 在运行时复制控制按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21953027/

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