我有一个这样的按钮:
<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。 我尝试了很多方法来解决这个问题,就像将内容放入样式......但没有运气。 你有什么想法或我做错了吗? 感谢
答案 0 :(得分: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);
}
}