很久没写Blogs了,如今在看【WPF编程宝典】,决定开始从新写博客,和你们一块儿分享技术。 编程
在编程时咱们常但愿界面是动态的,能够随时变换而不须要从新编译本身的代码。 ide
如下是动态加载XAML的一个事例代码。 spa
在debug文件夹下新建一个文本文件,重命名为:file.xaml debug
插入界面代码: xml
<DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> 博客 <Button Name="button1" Margin="30" Content="Pleas click me."></Button> string </DockPanel>it |
在VS新建LoadXAML.CS类。 io
public class LoadXAML :Window 编译 { private Button button1;
public LoadXAML(string xamlFile) { Width = Height = 285; Left = Top = 100; Title = "动态加载XAML";
DependencyObject rootElement; using (FileStream fs=new FileStream(xamlFile, FileMode.Open)) { rootElement =(DependencyObject) XamlReader.Load(fs);
} Content = rootElement; //查找控件(方法一) //button1 = (Button) LogicalTreeHelper.FindLogicalNode(rootElement, "button1");
//查找控件(方法二) FrameworkElement frameworkElement = (FrameworkElement) rootElement; button1 = (Button) frameworkElement.FindName("button1");
button1.Click += button1_Click; }
void button1_Click(object sender, RoutedEventArgs e) { button1.Content = "Thank you."; } |
修改App.xaml启动项
protected override void OnStartup(StartupEventArgs e) { var win = new LoadXAML("file.xaml"); win.Show(); } |