2011-10-11 43 views
0

我想獲得適用於特定控件類型的樣式列表。我想要做下面的代碼,但不必指定密鑰名稱並獲取適用的資源列表。這可能嗎?獲取特定TargetType的樣式列表

ComponentResourceKey key = new ComponentResourceKey(typeof(MyControlType), ""); 
Style style = (Style)Application.Current.TryFindResource(key); 

回答

1

會是否有意義首先檢查你的控制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。我希望這可以是一個很好的起點。乾杯!

+0

很好的解決方案,但請注意它不會總是有效。在您使用Visual Tree時,將無法找到來自TabItem的資源。 – Max