我想问一下WPF中可否像html一样,获取所有的xaml对象,包括后台代码动态添加的控件对象,并且可以通过获取到的xaml加载到页面中的方法谢谢。
可以加分
获取所有的控件:
private void btnLoadXAML_Click(object sender, RoutedEventArgs e) { try { OpenFileDialog Fd = new OpenFileDialog(); Fd.ShowDialog(); string LoadedFileName = Fd.FileName; //加载XAML文件 FileStream Fs = new FileStream(@LoadedFileName, FileMode.Open); Grid grdToLoad = new Grid(); grdToLoad.Height = 210; grdToLoad.Width = 400; grdToLoad = System.Windows.Markup.XamlReader.Load(Fs) as Grid; grdLoadXAML.Children.Add(grdToLoad); Fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
这是把获取的代码加载到XAML文件中:
private void btnCreateXAML_Click(object sender, RoutedEventArgs e) { try { Grid grd = new Grid(); grd.Height = 210; grd.Width = 400; Button btn = new Button(); btn.Height = 50; btn.Width = 80; btn.Content = "Dyn. Button"; btn.Background = new SolidColorBrush(Colors.Red); btn.Margin = new Thickness(5, 5, 310, 120); grd.Children.Add(btn); TextBox txt = new TextBox(); txt.Height = 50; txt.Width = 100; txt.Text = "Dynamic TextBox"; txt.Foreground = new SolidColorBrush(Colors.Red); txt.Margin = new Thickness(5, 60, 310, 80); grd.Children.Add(txt); //保存Xaml文件 FileStream Fs = new FileStream(@"H:\GeneratedFiles\MyDesign.Xml", FileMode.CreateNew); System.Windows.Markup.XamlWriter.Save(grd, Fs); Fs.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
大致思路就是这些了,你根据你的需要改动一下。
先谢谢,不过看第一段代码的意思貌似没有读当前窗体的xaml,我试试。谢谢。
@邵明瑞: 你把路径改成你的当前xaml的路径。
大神,这种方式System.Windows.Markup.XamlWriter.Save(grd, Fs);获取不到例如Button中的Click属性,这种情况怎么获取,谢谢指点
myxaml1.txt内容
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Button Height="55" Margin="100,115,0,0" Name="button1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="142">Button</Button>
<Button Height="55" Margin="291,115,166,0" Name="button2" VerticalAlignment="Top">Button</Button>
</Grid>
获取文件内容,并且加载到页面
/// <summary>
/// 动态添加控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, RoutedEventArgs e)
{
DependencyObject bto = new Button();
Button bt = (Button)bto;
bt.Margin = new Thickness(2,2,0,0);
bt.Width = 100;
bt.Height = 100;
bt.Content = "hello";
g1.Children.Add(bt);
}
/// <summary>
/// 动态加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, RoutedEventArgs e)
{
Stream sm = File.OpenRead(@"myxaml1.txt");
DependencyObject element = (DependencyObject)XamlReader.Load(sm);
this.Content = element;
}
万分感谢!
获取呢。