xaml代码:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded_1">
<Grid>
<Button Content="button" Margin="179,131,206,150"></Button>
</Grid>
</Window>
后台cs代码:
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
StringBuilder tree = new StringBuilder();
PrintVisualTree(this, 0, tree);
Console.WriteLine("VisualTree:");
Console.WriteLine(tree.ToString());
tree.Clear();
PrintLogicalTree(this, 0, tree);
Console.WriteLine("LogicalTree:");
Console.WriteLine(tree.ToString());
}
public void PrintVisualTree(DependencyObject obj, int level, StringBuilder tree)
{
tree.AppendLine(new string(' ', level) + obj);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
PrintVisualTree(VisualTreeHelper.GetChild(obj, i), level + 1, tree);
}
}
public void PrintLogicalTree(DependencyObject obj, int level, StringBuilder tree)
{
tree.AppendLine(new string(' ', level) + obj);
foreach (var v in LogicalTreeHelper.GetChildren(obj))
{
if (v is DependencyObject)
{
PrintLogicalTree(v as DependencyObject, level + 1, tree);
}
}
}
//输出
VisualTree:
WpfApplication1.MainWindow
System.Windows.Controls.Border
System.Windows.Documents.AdornerDecorator
System.Windows.Controls.ContentPresenter
System.Windows.Controls.Grid
System.Windows.Controls.Button: button
Microsoft.Windows.Themes.ButtonChrome
System.Windows.Controls.ContentPresenter
System.Windows.Controls.TextBlock
System.Windows.Documents.AdornerLayer
LogicalTree:
WpfApplication1.MainWindow
System.Windows.Controls.Grid
System.Windows.Controls.Button: button
从视觉树的结构中可以看到,Button的Content是显示在TextBlock上的,所以,我们可以通过查找视觉树来修改Button的Content样式。
private void buttonSunny_Click_1(object sender, RoutedEventArgs e)
{
ChangeVisualTree<TextBlock>(this);
}
public void ChangeVisualTree<T>(DependencyObject obj) where T : FrameworkElement
{
if (obj is T)
{
switch (typeof(T).Name)
{
case "TextBlock":
TextBlock textBlock = obj as TextBlock;
textBlock.Background = Brushes.Yellow;
textBlock.Foreground = Brushes.Brown;
break;
default:
break;
}
}
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
ChangeVisualTree<T>(VisualTreeHelper.GetChild(obj, i));
}
}
通过 WPF Inspector可以更加详细地了解WPF应用的树形结构和样式等,也可以修改样式,用法很简单,先运行WPF应用,然后打开WPF Inspector,等其加载完成之后,双击列表中的应用即可。