[Wpf学习] 2.代码导入Xaml
程序员文章站
2022-05-03 11:19:50
废话不说,直接上代码 有了这玩意,似乎打开了一扇窗——前后端真正分离? ......
废话不说,直接上代码
using system.componentmodel; using system.runtime.compilerservices; using system.windows; using system.windows.controls; using system.windows.markup; namespace l2_core_loadxaml { /// <summary> /// interaction logic for mainwindow.xaml /// </summary> public partial class mainwindow : window { public class vm : inotifypropertychanged { public event propertychangedeventhandler propertychanged; public void raisepropertychanged([callermembername] string propertyname = "") { propertychanged?.invoke(this, new propertychangedeventargs(propertyname)); } private string _a; public string a { get => _a; set { _a = value; raisepropertychanged(); } } } public mainwindow() { initializecomponent(); this.datacontext = new vm() { a = "hello" }; this.loaded += mainwindow_loaded; } private void mainwindow_loaded(object sender, routedeventargs e) { string xaml = @" <grid xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> <button name=""button1"" content=""{binding a}""></button> </grid > "; var rootelement = (dependencyobject)xamlreader.parse(xaml); this.content = rootelement; button button1 = (button)logicaltreehelper.findlogicalnode(rootelement, "button1"); button1.click += (o, e) => messagebox.show("xaml loaded!"); } } }
有了这玩意,似乎打开了一扇窗——前后端真正分离?