1

我有一个这样的按钮:

 <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>

此按钮在 FormA 内,打开 FormB 时,我想将 btnSave 克隆到 FormB,但它只是创建了一个 Content = null 按钮。

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

调试时,btnSave.Content 始终 = null。我尝试了很多方法来解决这个问题,比如将内容放入样式中......但没有运气。你有什么想法还是我做错了什么?谢谢

4

1 回答 1

2

将对象另存为 xaml,然后从该 xaml 创建一个新对象。这是一个简单的示例,其中一个按钮在单击时会自行克隆并添加到堆栈面板中。

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>

代码隐藏

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);

    }
}
于 2013-10-04T17:49:22.753 回答