MARK
MARK

Reputation: 424

Copy control button in run time

Hi all. I create an application with some (WPF) forms. I have a button on one form. I want to, at run time, copy this button onto a second form without having to create it again.

For example: I have 'X' button on form 1. At run time, I create a copy of this button on form 2 with all of the same property values as the original button on form 1.

The button:

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

Any chance I can avoid having to reproduce this code?

Upvotes: 2

Views: 695

Answers (2)

ouflak
ouflak

Reputation: 2508

If you want to create an exact clone, then you will need to serialize the component and inject an ExpressionConverter into the serialization process. This will create a 'deep' clone. See here.

Upvotes: 0

kmatyaszek
kmatyaszek

Reputation: 19296

You can define your own style for button in 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>

Code behind:

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

And when you want to assign created earlier style to the button, you should use StaticResource and name of your style:

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

Upvotes: 1

Related Questions