Quoc Nguyen
Quoc Nguyen

Reputation: 360

Can't clone Button with custom Content

I have a button like this:

 <Button Name="btnSave" Click="BtnSave_OnClick"  Margin="5,0,0,0" MinWidth="50" ToolTip="SAVE">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Image Height="24" HorizontalAlignment="Center" Source="/MyProject;component/Images/diskette.png" Width="24" />
                        <TextBlock Grid.Row="1" HorizontalAlignment="Center" Text="SAVE" />
                    </Grid>
            </Button>

This button is inside FormA, when opening FormB i want to clone btnSave to FormB but it just created a Content = null button.

// On formA
FormB formB = new FormB();
formB.Loaded += (s, e1) =>
                {                       
                        formA.Children.Remove(btnSave);
                        formB.Children.Add(btnSave);
                };
formB.Show();

When debugging, btnSave.Content always = null. I tried many way to fix this issue like as put Content into Style... but no luck. Do you have any idea or i do something wrong? Thanks

Upvotes: 1

Views: 427

Answers (1)

mdm20
mdm20

Reputation: 4563

Save the object as xaml and then create a new object from that xaml. Here's a simple example where a button clones itself when clicked and gets added to a stackpanel.

Xaml

<StackPanel x:Name="MainStackPanel">
    <Button Name="btnSave" Click="BtnSave_OnClick"  Margin="5,0,0,0" MinWidth="50" ToolTip="SAVE" >
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <Image Height="24" HorizontalAlignment="Center" Source="/MyProject;component/Images/diskette.png" Width="24" />
            <TextBlock Grid.Row="1" HorizontalAlignment="Center" Text="SAVE" />
        </Grid>
    </Button>
</StackPanel>

Codebehind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void BtnSave_OnClick(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;
        string xaml = XamlWriter.Save(button);
        object clonedButton = XamlReader.Parse(xaml);
        MainStackPanel.Children.Add(clonedButton as UIElement);

    }
}

Upvotes: 2

Related Questions