會是否有意義首先檢查你的控制Resources
,然後繼續走了VisualTree
檢查Resources
沿途模擬WPF如何找到資源的控制(包括Styles
)?
例如,也許你可以創建一個擴展方法,它這給予了FrameworkElement
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
namespace WpfApplication2
{
public static class FrameworkElementHelper
{
public static IEnumerable<Style> FindStylesOfType<TStyle>(this FrameworkElement frameworkElement)
{
IEnumerable<Style> styles = new List<Style>();
var node = frameworkElement;
while (node != null)
{
styles = styles.Concat(node.Resources.Values.OfType<Style>().Where(i => i.TargetType == typeof(TStyle)));
node = VisualTreeHelper.GetParent(node) as FrameworkElement;
}
return styles;
}
}
}
一看就知道這工作,創建具有隱式和在VisualTree
多層次明確Styles
XAML文件:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfApplication2"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" SizeToContent="WidthAndHeight">
<Window.Resources>
<Style TargetType="{x:Type Button}" />
<Style x:Key="NamedButtonStyle" TargetType="{x:Type Button}" />
<Style TargetType="{x:Type TextBlock}" />
<Style x:Key="NamedTextBlockStyle" TargetType="{x:Type TextBlock}" />
</Window.Resources>
<StackPanel>
<TextBlock x:Name="myTextBlock" Text="No results yet." />
<Button x:Name="myButton" Content="Find Styles" Click="OnMyButtonClick">
<Button.Resources>
<Style TargetType="{x:Type Button}" />
<Style x:Key="NamedButtonStyle" TargetType="{x:Type Button}" />
<Style TargetType="{x:Type TextBlock}" />
<Style x:Key="NamedTextBlockStyle" TargetType="{x:Type TextBlock}" />
</Button.Resources>
</Button>
</StackPanel>
</Window>
,並在以下代碼後面的處理程序:
private void OnMyButtonClick(object sender, RoutedEventArgs e)
{
var styles = myButton.FindStylesOfType<Button>();
myTextBlock.Text = String.Format("Found {0} styles", styles.Count());
}
在此示例中,找到了myButton
的4種樣式,其中所有樣式的TargetType
均爲Button
。我希望這可以是一個很好的起點。乾杯!
很好的解決方案,但請注意它不會總是有效。在您使用Visual Tree時,將無法找到來自TabItem的資源。 – Max