[WPF] 新的UI Debugging Tools for XAML簡介
前幾天發佈的Visual Studio 2015 CTP 6版本中,新增了一項很棒的功能UI Debugging Tools for XAML,這功能讓開發者在debug時馬上就可以即時看到當時介面的Visual Tree結構以及property,馬上就做個簡單範例來試用一下
介面的xaml如下:
<Window x:Class="WpfApplication1.MainWindow" | |
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | |
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | |
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" | |
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" | |
xmlns:local="clr-namespace:WpfApplication1" | |
mc:Ignorable="d" | |
Title="MainWindow" Height="350" Width="525"> | |
<Grid> | |
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="47" Margin="110,63,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="159"/> | |
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Height="38" Margin="110,110,0,0" VerticalAlignment="Top" Width="96"/> | |
<Rectangle Fill="#FF3B3BDC" HorizontalAlignment="Left" Height="46" Margin="90,171,0,0" Stroke="Black" VerticalAlignment="Top" Width="126"/> | |
<ListBox Name="TestListBox" Width="70" Margin="274,50,193,0"> | |
<ListBox.ItemTemplate> | |
<DataTemplate> | |
<TextBlock Text="{Binding}"/> | |
</DataTemplate> | |
</ListBox.ItemTemplate> | |
</ListBox> | |
</Grid> | |
</Window> |
然後在程式中簡單的給予ListBox幾個數字binding
using System.Collections.Generic; | |
using System.Windows; | |
namespace WpfApplication1 | |
{ | |
/// <summary> | |
/// Interaction logic for MainWindow.xaml | |
/// </summary> | |
public partial class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
List<int> numbers = new List<int>(); | |
for (int i = 0; i < 5; i++) | |
{ | |
numbers.Add(i); | |
} | |
TestListBox.ItemsSource = numbers; | |
} | |
} | |
} |
直接執行debug後,VS介面左右邊會出現Live Visual Tree跟Live Property Explorer兩個panel,Live Visual Tree顯示的就是當時介面的Visual Tree結構,而panel中框起來的數字可以知道裡面的節點個數,右邊的Live Property Explorer則會顯示選到物件的屬性
而Live Visual Tree的第一個按鈕(enable selection in the running application)可以讓我們選取執行程式介面中的物件,跟瀏覽器的開發者工具裡的選取元素(Inspect Element)類似的意思,被選中的會有紅點框起來
另外第二個按鈕(display layout adorners in the running application)按下後,被選中的物件如下圖一樣還會顯示格線
接著再看到Live Visual Tree panel,像ListBox裡面的item我們是databinding來的,並不是原本在xaml裡就一個個宣告,但在這裡顯示的Visual Tree結構真的還是非常完整的解析出來
再看到右邊的Live Property Explorer panel,這是在debug中直接去改變Button的Text屬性,也會立即反應到執行程式中的介面
PS:目前版本在這裡改變的所有值都不會真的去修改原始的xaml
要改變Rectangle的color、width、Height或位置等屬性也沒問題
這功能對開發xaml介面來說真的是非常實用,特別是有時候如果複雜一點的datatemplate,現在都可以在執行時直接看到完整的Visual Tree結構,不過可惜目前這功能只在WPF的開發上才有,Windows APP的開發還沒有,但應該是可以期待未來Windows APP一定也會有所支援(希望可以趕在RTM時XD)
Reference