1. 程式人生 > 實用技巧 >WPF中的Data Binding除錯指南

WPF中的Data Binding除錯指南

大家平時做WPF開發,相信用Visual studio的小夥伴比較多。XAML裡面曾經在某些特殊版本的Visual Studio中是可以加斷點進行除錯的,不過目前多數版本都不支援在XAML加斷點來除錯。

那如果自己需要繫結的 Property 沒生效,該怎麼去檢測或Debug排查問題呢?下面大白給出幾種自己用過的方法,本人的開發環境是 Win10專業版x64 + Visual Studio 2019專業版v16.2.2,以下方法都親測有效。

方法1: 修改登入檔 + 修改config檔案

在登入檔中增加一個選項,

具體做法是,在目錄HKEY_CURRENT_USER\Software\Microsoft

中建立資料夾Tracing, 然後在其裡面建立子資料夾WPF,然後新建一個DWORD(32位)值ManagedTracing,將其值設定為1.

也可以將下面的檔案另存為 trace.reg,然後雙擊進行設定。

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Tracing\WPF]
"ManagedTracing"=dword:00000001

接下來,需要在你的Project的能影響 .exe.config生成的那個 .config檔案下加入摺疊區域的內容:

由於我這邊相關的config檔案就是App.config

,所以只需在App.config中加入該內容。

圖中摺疊的部分如下:

  <system.diagnostics>
<sources>
<source name="System.Windows.Data" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <!--<source name="System.Windows.Data" switchName="BindingSwitch" >
<listeners>
<add name="BindingXmlListener" />
</listeners>
</source>--> <source name="System.Windows.DependencyProperty" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <source name="System.Windows.Freezable" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <source name="System.Windows.RoutedEvent" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <source name="System.Windows.Media.Animation" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <source name="System.Windows.NameScope" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <source name="System.Windows.ResourceDictionary" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <source name="System.Windows.Markup" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <source name="System.Windows.Documents" switchName="BindingSwitch" >
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> </sources> <switches>
<add name="BindingSwitch" value="All" />
<!--add name="BindingSwitch" value="Off" -->
<!--add name="BindingSwitch" value="Verbose" -->
<!--add name="BindingSwitch" value="Warning" -->
<!--add name="BindingSwitch" value="Activity" -->
</switches>
<sharedListeners>
<!-- This listener sends output to a file named BindingTrace.log (text) -->
<add name="BindingTextListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="BindingTrace.log" /> <!-- This listener sends output to the console -->
<add name="console" type="System.Diagnostics.ConsoleTraceListener" initializeData="false"/> <!-- This listener sends output to an Xml file named BindingTrace.xml -->
<add name="BindingXmlListener" type="System.Diagnostics.XmlWriterTraceListener" traceOutputOptions="None" initializeData="BindingTrace.xml" />
</sharedListeners> <trace autoflush="true" indentsize="4"></trace>
</system.diagnostics>

設定好後,你build這個wpf專案後,當啟動Debug時,在其相應的debug目錄下會多出一個 BindingTrace.log檔案,比如, 我這邊的內容上這樣的:

我配置監聽器(listener)時,將debug的資訊設定成了.log格式,與.txt格式相比其優勢是: 當用vs code開啟時,自帶高亮,看起來比較爽。

      <!-- This listener sends output to a file named BindingTrace.log (text) -->
<add name="BindingTextListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="BindingTrace.log" />

當然也有小夥伴希望將Trace資訊匯出為xml,也可以的,只需將加入內容開頭部分的:

  <source>
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> <!--<source name="System.Windows.Data" switchName="BindingSwitch" >
<listeners>
<add name="BindingXmlListener" />
</listeners>
</source> -->

改為:

  <!-- <source>
<listeners>
<add name="BindingTextListener" />
</listeners>
</source> --> <source name="System.Windows.Data" switchName="BindingSwitch" >
<listeners>
<add name="BindingXmlListener" />
</listeners>
</source>

即可。

那麼,此時在其相應的debug目錄下會多出一個 BindingTrace.xml檔案,我這邊的內容上這樣的:

參考:

https://systemscenter.ru/scsm_authoringtool.en/html/b24efd85-0ced-48ea-8ecc-d816c789bae2.htm

https://www.cnblogs.com/furenjun/archive/2011/08/01/2123983.html

WPF Tutorial | Debug DataBinding Issues

https://www.wpftutorial.net/DebugDataBinding.html

old-wpf-blog/45-DebuggingDataBinding at master · bstollnitz/old-wpf-blog

https://github.com/bstollnitz/old-wpf-blog/tree/master/45-DebuggingDataBinding

方法2: 在XAML中設定TraceLevel + 在xaml中需要debug的View對應的 .xaml.cs檔案中啟用WPF Trace

該方法適用於 .NET framework 3.5以後(包括 .NET core)的WPF project.

首先需要給該View的xaml檔案的某個節點加入 PresentationTraceSources.TraceLevel="High",

<UserControl x:Class="CaliburnMicro_Calculator.Views.CalculatorView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CaliburnMicro_Calculator.Views"
xmlns:cal="http://www.caliburnproject.org"
mc:Ignorable="d"
Width="240">

我這邊直接在這個view的根節點<UserControl>中加入 PresentationTraceSources.TraceLevel="High",結果如下:

<UserControl x:Class="CaliburnMicro_Calculator.Views.CalculatorView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CaliburnMicro_Calculator.Views"
xmlns:cal="http://www.caliburnproject.org"
mc:Ignorable="d"
Width="240" PresentationTraceSources.TraceLevel="High">

此時,我們還需要在目標View的對應的 .xaml.cs檔案中啟用WPF Trace.

            // Enable WPF tracing
PresentationTraceSources.Refresh();
PresentationTraceSources.DataBindingSource.Listeners.Add(new ConsoleTraceListener());
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.All;

此時,在Output(輸出視窗)就可以看到資料繫結的相關資訊了。

可能有人會好奇output中的紅色字型是怎麼來的,vs的output預設是黑色。

其實安裝一個vs外掛VSColorOutput就好了,傳送門:

https://marketplace.visualstudio.com/items?itemName=MikeWard-AnnArbor.VSColorOutput.

當然,你還可以在此時啟用"診斷工具",位置是: 除錯 -> 視窗 -> 顯示診斷工具,配合起來用起來更爽喔~

方法3: Visual Studio 2019 (16.4之後的版本)安裝 XAML binding extension

這個VS外掛由微軟XAML團隊推出,看起來像是實現了方法1或方法2的自動化。

XAML binding extension for Visual Studio 2019 下載地址:

https://marketplace.visualstudio.com/items?itemName=PeterSpa.XamlBinding

相關程式碼已開源:

spadapet/xaml-binding-tool: XAML binding error window in a Visual Studio 2019 extension

https://github.com/spadapet/xaml-binding-tool

當安裝好這個外掛時,重啟VS就可以用了,debug時,除錯視窗中會多一個選項"XAML binding failures (experimental)"。點選該選項,debug相關視窗中會顯示Data binding的詳細資訊。

此時,WPF trace level附近的...還可以點選進行設定。

方法4: 使用第三方debug工具 WPF

首推Snoop,這個工具大概2006年就出來了,歷史悠久,最初由微軟Blend團隊的Pete Blois開發,功能也異常強大,而且目前也一直有人維護和更新。

左上角支援filter,屬性或層級很多時,可以快速定位目標節點。

Snoop中的Tree, Properties, Data Context均支援filter,而Properties和Data Context都可以打斷點。

當屬性值更改,整個屬性的背景更改為黃色高亮一秒鐘,以吸引使用者注意。

Snoop允許您檢視您在應用程式中指定的事件列表。當您單擊元素時,您可以看到哪些元素受到影響,並檢視哪個(方法或任何人)處理該點選。Hanlded的事件以綠色顯示。這是Snoop提供的檢視隧道和事件冒泡傳遞之間的區別的強有力方法,特別是當這些事件處理得太快或根本不處理,它們如何影響您的視覺化元素。

當出現binding error時,可以選擇應用程式右側的屬性,然後右鍵單擊以深入瞭解繫結或繫結表示式,以便給出更詳細的錯誤說明。

在Snoop的左上角,有一個下拉框可以開啟,然後選擇"Show only Visuals with binding Errors"以檢視應用程式所具有的可視資料繫結錯誤列表。

Snoop 的一個眾所周知的功能是能夠識別資料繫結問題。當看到元件是否繫結正確時,我通常只是嘗試一下,看看它是否有效。如果無效,我轉向 Visual Studio 除錯模式下的output視窗。如果無法立即看到該值,我會這樣做:將 Snoop 附加(Attach)到我的應用,並從應用程式樹檢視上方的搜尋/篩選器欄中選擇"Show only visuals with binding errors"選項。

Attach和Debug的步驟如下:

  • 以管理員許可權啟動snoop
  • 在程式碼裡面的合適地方加上斷點
  • Ctrl + F5 執行專案
  • 重現需要debug的介面
  • 除錯 -> Debug -> 附加到程式(Attach)

然後在snoop上依次點:

Refresh按鈕, Snoop按鈕(望遠鏡),藉助filter找需要inspect的目標元素,接下來 debug就比較順暢了。

還可以使用它來顯示任何具有繫結錯誤(Binding error)的控制元件(就像word中的拼寫檢查一樣):

Snoop 中的繫結錯誤會紅色高亮顯示

也有小夥伴在用或WPF Inspector,不過這個工具好久沒更新了。

WPF Inspector 這個專案之前是在CodePlex上的,後來沒人維護了,目前有人手動fork到github上,但沒見任何更新。

還有小夥伴用 Mole這個Visual Studio 外掛,有興趣的朋友可以去試試~

Mole for Visual Studio外掛下載:

Mole for VS 2015 is installed from the Visual Studio Marketplace.

Mole for VS 2017 is installed from the Visual Studio Marketplace.

Mole for VS 2019 is installed from the Visual Studio Marketplace.

其他方法:

  • Binding改為x:Binding後進行除錯
  • 增加一個 ValueConverter,呼叫它進行除錯

這兩種本人不太熟悉,有興趣的可以自己去試試哈~