解读WPF中的Xaml
1.Overview
這篇文章主要分享從源代碼角度解讀wpf中xaml。由于源碼查看起來錯綜復雜“隨便找一個對象按下F12就是一個新的世界”,看源碼的感覺就是在盜夢空間里來回穿梭;所以也是耗費很長的時間去閱讀源碼然后根據自己的理解編寫文章和貼出部分關鍵源碼。
2.Detail
大概將從編譯、讀取、加載這幾個維度來解讀。以防后面看源碼會暈,先直接講結果;
編寫(可通過vs完成)
編譯(可通過vs完成)
讀取、加載
有的帥氣的觀眾就會問了,這些研究在實際在項目中應用場景是什么?
? ? ? ? ?選擇性的加載xaml(baml)文件來達到更改UI的操作。
動態換膚,大家都用過手機app每到過年過節都會看到界面上會出現對應的主題,那么我們就可以在程序內設定到了某個節日直接加載對應主題界面的xaml(baml)文件來達到這種效果,對于動態皮膚場景來說,在運行時加載和解析XAML是有意義的。
加載不同的.xaml(.baml)文件,以適應不同分辨率的布局
簡單固定的UI美工人員將設計稿轉換為位圖,可使用blend或者 expression design轉成對應的wpf界面
還可以適配不同的業務要求。可能這種延伸就是研究的意義吧
(1)編譯xaml
XAML不僅要能夠解決涉及協作問題,它還需要快速運行。盡管基于XML格式可以很靈活并且很容易地遷移到其他平臺和工具,但未必是有效的選擇。XML的涉及目標是具有邏輯性、易讀而且簡單,沒有被壓縮。WPF 使用 BAML(Binaiy Application Markup Language,二進制應用程序標記語言)來克服這 個缺點。BAML 并非新事物,它實際上就是 XAML 的二進制表示,當在 Visual Studio 中編譯 WPF 應用程序時,所有 XAML 文件都被轉換為 BAML這些 BAML 然后作為資源被嵌入到最 終的 DLL 或 EXE 程序集中。BAML 是標記化的,這意味著較長的 XAML 被較短的標記替代。BAML 不僅明顯小一些,還對其進行了優化,從而使它在運行時能夠更快地解析。并成為一個內嵌資源;
BAML由VS編譯生成存在,obj目錄的debug下;
通過IL反編譯項目文件之后,可以看到編譯完成之后將會被連接到工程的“資源清單”當中。
使用Assembly的GetManifestResourceStream方法,可以在運行期獲取到這個二進制流
(2)讀取、加載xaml(baml)
使用代碼和未經編譯的標記(XAML),這種具體方式對于某些特殊情況是很苻意義的* 例如創建高度動態化的用戶界面。這種方式在運行時使用 System.Windows.Markup 名 稱空間中的 從 XAML 文件中加載部分用戶界面。使用代碼和編譯過的標記(BAML),對于 WPF 而言這是一種更好的方式,也是 Visual Studio 支持的一種方式。這種方式為每個窗口創建一個 XAML 橫板,這個 XAML 模板 被編譯為 BAML,并嵌入到最終的程序集中。編譯過的 BAML 在運行時被提取出來, 用于重新生成用戶界面。
1.當客戶端程序被啟動時Runtime接管代碼來創建window實例
2.Window構造函數調用Application.LoadComponent讀取創建.xaml(baml)
IL反編譯后的代碼
3.Application.LoadComponent()加載baml
? ? ? XamlReader.LoadBaml細節代碼
internal static object LoadBaml(Stream stream,ParserContext parserContext,object parent,bool closeStream) {object p1 = (object) null;EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Event.WClientParseBamlBegin, (object) parserContext.BaseUri);if (TraceMarkup.IsEnabled)TraceMarkup.Trace(TraceEventType.Start, TraceMarkup.Load);try{if (stream is IStreamInfo streamInfo2)parserContext.StreamCreatedAssembly = streamInfo2.Assembly;Baml2006ReaderSettings bamlReaderSettings = XamlReader.CreateBamlReaderSettings();bamlReaderSettings.BaseUri = parserContext.BaseUri;bamlReaderSettings.LocalAssembly = streamInfo2.Assembly;if (bamlReaderSettings.BaseUri == (Uri) null || string.IsNullOrEmpty(bamlReaderSettings.BaseUri.ToString()))bamlReaderSettings.BaseUri = BaseUriHelper.PackAppBaseUri;Baml2006ReaderInternal baml2006ReaderInternal = new Baml2006ReaderInternal(stream, new Baml2006SchemaContext(bamlReaderSettings.LocalAssembly), bamlReaderSettings, parent);Type type = (Type) null;if (streamInfo2.Assembly != (Assembly) null){try{type = XamlTypeMapper.GetInternalTypeHelperTypeFromAssembly(parserContext);}catch (Exception ex){if (CriticalExceptions.IsCriticalException(ex))throw;}}if (type != (Type) null){XamlAccessLevel xamlAccessLevel = XamlAccessLevel.AssemblyAccessTo(streamInfo2.Assembly);new XamlLoadPermission(xamlAccessLevel).Assert();try{p1 = WpfXamlLoader.LoadBaml((System.Xaml.XamlReader) baml2006ReaderInternal, parserContext.SkipJournaledProperties, parent, xamlAccessLevel, parserContext.BaseUri);}finally{CodeAccessPermission.RevertAssert();}}elsep1 = WpfXamlLoader.LoadBaml((System.Xaml.XamlReader) baml2006ReaderInternal, parserContext.SkipJournaledProperties, parent, (XamlAccessLevel) null, parserContext.BaseUri);if (p1 is DependencyObject dependencyObject2)dependencyObject2.SetValue(BaseUriHelper.BaseUriProperty, (object) bamlReaderSettings.BaseUri);if (p1 is Application application2)application2.ApplicationMarkupBaseUri = XamlReader.GetBaseUri(bamlReaderSettings.BaseUri);}finally{if (TraceMarkup.IsEnabled)TraceMarkup.Trace(TraceEventType.Stop, TraceMarkup.Load, p1);EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Event.WClientParseBamlEnd, (object) parserContext.BaseUri);if (closeStream && stream != null)stream.Close();}return p1; }4.加載控件對象
提取BAML(編譯過的XAML)解析并創建每個定義的控件對象,設置屬性、關聯事件等內容。
internal static object LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc) {if (Application.s_NestedBamlLoadInfo == null)Application.s_NestedBamlLoadInfo = new Stack<NestedBamlLoadInfo>();NestedBamlLoadInfo nestedBamlLoadInfo = new NestedBamlLoadInfo(pc.BaseUri, stream, pc.SkipJournaledProperties);Application.s_NestedBamlLoadInfo.Push(nestedBamlLoadInfo);try{return XamlReader.LoadBaml(stream, pc, (object) null, true);}finally{Application.s_NestedBamlLoadInfo.Pop();if (Application.s_NestedBamlLoadInfo.Count == 0)Application.s_NestedBamlLoadInfo = (Stack<NestedBamlLoadInfo>) null;} }循環遍歷所有xaml里的標簽節點生成窗體內的內容。
private static object Load(System.Xaml.XamlReader xamlReader,IXamlObjectWriterFactory writerFactory,bool skipJournaledProperties,object rootObject,XamlObjectWriterSettings settings,Uri baseUri) {XamlContextStack<WpfXamlFrame> stack = new XamlContextStack<WpfXamlFrame>((Func<WpfXamlFrame>) (() => new WpfXamlFrame()));int persistId = 1;settings.AfterBeginInitHandler = (EventHandler<XamlObjectEventArgs>) ((sender, args) =>{if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose)){IXamlLineInfo xamlLineInfo = xamlReader as IXamlLineInfo;int num1 = -1;int num2 = -1;if (xamlLineInfo != null && xamlLineInfo.HasLineInfo){num1 = xamlLineInfo.LineNumber;num2 = xamlLineInfo.LinePosition;}int num3 = (int) EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientParseXamlBamlInfo, EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, (object) (args.Instance == null ? 0L : PerfService.GetPerfElementID(args.Instance)), (object) num1, (object) num2);}if (args.Instance is UIElement instance3){int num = persistId++;instance3.SetPersistId(num);}XamlSourceInfoHelper.SetXamlSourceInfo(args.Instance, args, baseUri);if (args.Instance is DependencyObject instance4 && stack.CurrentFrame.XmlnsDictionary != null){XmlnsDictionary xmlnsDictionary = stack.CurrentFrame.XmlnsDictionary;xmlnsDictionary.Seal();XmlAttributeProperties.SetXmlnsDictionary(instance4, xmlnsDictionary);}stack.CurrentFrame.Instance = args.Instance;});XamlObjectWriter xamlWriter = writerFactory == null ? new XamlObjectWriter(xamlReader.SchemaContext, settings) : writerFactory.GetXamlObjectWriter(settings);IXamlLineInfo xamlLineInfo1 = (IXamlLineInfo) null;try{xamlLineInfo1 = xamlReader as IXamlLineInfo;IXamlLineInfoConsumer xamlLineInfoConsumer = (IXamlLineInfoConsumer) xamlWriter;bool shouldPassLineNumberInfo = false;if (xamlLineInfo1 != null && xamlLineInfo1.HasLineInfo && xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)shouldPassLineNumberInfo = true;IStyleConnector styleConnector = rootObject as IStyleConnector;WpfXamlLoader.TransformNodes(xamlReader, xamlWriter, false, skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo1, xamlLineInfoConsumer, stack, styleConnector);xamlWriter.Close();return xamlWriter.Result;}catch (Exception ex){if (CriticalExceptions.IsCriticalException(ex) || !XamlReader.ShouldReWrapException(ex, baseUri)){throw;}else{XamlReader.RewrapException(ex, xamlLineInfo1, baseUri);return (object) null;}} }// Get the XAML content from an external file. DependencyObject rootElement; using (FileStream fs = new FileStrearn(xamlFile, FileMode Open)){ rootElement = (DependencyObject)XamlReader.Load(fs); }// Insert the markup into this window. this.Content = rootElement; // Find the control with the appropriate buttonl = (Button)LogicalTreeHelper.FindLogicalNode(rootElement, ibuttonl"); name. // Wire up the event handler. buttonl.Click += buttonl 'Click【截選內容1,這一段引用lindexi文章內的內容,原文地址在文章末尾】在 WPF 中,在 XAML 里面定義的對象的創建,實際上不是完全通過反射來進行創建的,在WPF框架里面,有進行了一系列的優化。將會通過 XamlTypeInvoker 的 CreateInstance 方法來進行對象的創建,而默認的 XamlTypeInvoker 的 CreateInstance 定義如下。還有其他精彩內容在原文里可以查看;
public virtual object CreateInstance(object[] arguments){ThrowIfUnknown();if (!_xamlType.UnderlyingType.IsValueType && (arguments == null || arguments.Length == 0)){object result = DefaultCtorXamlActivator.CreateInstance(this);if (result != null){return result;}}return CreateInstanceWithActivator(_xamlType.UnderlyingType, arguments);}private object CreateInstanceWithActivator(Type type, object[] arguments){return SafeReflectionInvoker.CreateInstance(type, arguments);}【截選內容2,這一段引用lindexi文章內的內容,原文地址在文章末尾】
在 EnsureConstructorDelegate 方法里面將會判斷如果對象是公開的,那么嘗試獲取默認構造函數,將默認構造函數做成委托。此時的性能將會是類型第一次進入的時候的速度比較慢,但是后續進入的時候就能使用委托創建,此時性能將會比較好。通過反射創建委托提升性能的方法,詳細請看 .NET Core/Framework 創建委托以大幅度提高反射調用的性能 - walterlv
private static bool EnsureConstructorDelegate(XamlTypeInvoker type) {// 如果類型初始化過構造函數創建,那么返回,這是緩存的方法if (type._constructorDelegate != null){return true;}// 如果不是公開的方法,那么將無法使用反射創建委托的科技if (!type.IsPublic){return false;}// 反射獲取對象的構造函數Type underlyingType = type._xamlType.UnderlyingType.UnderlyingSystemType;// Look up public ctors only, for equivalence with Activator.CreateInstanceConstructorInfo tConstInfo = underlyingType.GetConstructor(Type.EmptyTypes);IntPtr constPtr = tConstInfo.MethodHandle.GetFunctionPointer();// 反射創建委托,這樣下次訪問就不需要使用反射,可以提升性能// This requires Reflection PermissionAction<object> ctorDelegate = ctorDelegate =(Action<object>)s_actionCtor.Invoke(new object[] { null, constPtr });type._constructorDelegate = ctorDelegate;return true; }也就是說只有第一次的類型進入才會調用反射創建委托用來提升性能,之后的進入將會使用第一次創建出來的委托來創建對象,這樣能提升性能。
4.Reference
dotnet/wpf: WPF is a .NET Core UI framework for building Windows desktop applications. (github.com)
dotnet 讀 WPF 源代碼筆記 XAML 創建對象的方法 (lindexi.com)
總結
以上是生活随笔為你收集整理的解读WPF中的Xaml的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 巧用ActionFilter的AOP特性
- 下一篇: .NET 也有 Husky 了