在运行时复制控制按钮

时间:2014-02-22 10:32:57

标签: c# wpf

大家好。我用一些(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" />

我有机会避免重现此代码吗?

2 个答案:

答案 0 :(得分:1)

您可以在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}" />

答案 1 :(得分:0)

如果要创建精确克隆,则需要序列化组件并将ExpressionConverter注入序列化过程。这将创建一个“深层”克隆。请参阅here

相关问题