使用 XamlReader 创建一个按钮,并增加事件,简单的代码,看看就明白了。
.cs代码:
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Markup;
- namespace test_xamlreader
- {
- public partial class MainPage : UserControl
- {
- private Button testBtn;
- int isCreated = 0;
- public MainPage()
- {
- InitializeComponent();
- }
- private void testBtn_Click(object sender, RoutedEventArgs e)
- {
- MessageBox.Show("ok");
- }
- private void Btn1_Click(object sender, RoutedEventArgs e)
- {
- if (isCreated == 0)
- {
- string xaml = string.Empty;
- xaml = "<Button xmlns=\"http://schemas.microsoft.com/client/2007\" Margin=\"14,11,19,12\" Width=\"120\" Height=\"26\" Content=\"TmpBtn\"/>";
- testBtn = XamlReader.Load(xaml) as Button;
- testBtn.Click += new RoutedEventHandler(testBtn_Click);
- this.LayoutRoot.Children.Add(testBtn);
- isCreated = 1;
- this.Btn1.Visibility = Visibility.Collapsed;
- }
- }
- }
- }
.xaml代码
- <UserControl x:Class="test_xamlreader.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d" designWidth="640" designHeight="480">
- <Grid x:Name="LayoutRoot">
- <Button x:Name="Btn1" Click="Btn1_Click" Margin="100,100,0,0" Width="120" Height="26" Content="Create"/>
- </Grid>
- </UserControl>