2012-03-01 51 views

回答

7

您需要訪問存儲樣式的XAML資源。通常他們的方式是將其存儲在單獨的資源文件中。然後,您需要以該ResourceDictionary對象的身份訪問該XAML文件的URI。這裏是一個例子,我使用轉換器來決定一個元素的樣式。

namespace Shared.Converters 
{ 
    public class SaveStatusConverter : IValueConverter 
    { 

    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 

     bool? saveState = (bool?)value; 
     Uri resourceLocater = new Uri("/Shared;component/Styles.xaml", System.UriKind.Relative); 
     ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater); 
     if (saveState == true) 
     return resourceDictionary["GreenDot"] as Style; 
     if (saveState == false) 
     return resourceDictionary["RedDot"] as Style; 
     return resourceDictionary["GrayDot"] as Style; 

    } 

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new System.NotImplementedException(); 
    } 
    } 
} 
2

如果你只是尋找一個例子,這裏有一個相對可用的一個:

http://www.shujaat.net/2010/10/wpf-style-selector-for-items-in.html

如果你有更具體的問題,我會建議張貼一些代碼/ XAML表示你已經什麼嘗試和你有什麼問題。

+0

我在XAML中創建了樣式,我只想返回在XAML中聲明的樣式。 – Never 2012-03-01 16:07:27

8

您可以將屬性添加到您的StyleSelector,然後使用屬性傳遞到在XAML中Style的參考。

public class MyStyleSelector : StyleSelector 
{ 
    private Style styleToUse; 

    public Style StyleToUse 
    { 
     get { return styleToUse; } 
     set { styleToUse = value; } 
    } 

    public override Style SelectStyle(object item, DependencyObject container) 
    { 
     return styleToUse; 
    } 
} 

<Control StyleSelector="{DynamicResource myStyleSelector}"> 
    <Control.Resources> 
     <Style x:Key="myStyle"> 
     ... 
     </Style> 
     <local:MyStyleSelector x:Key="myStyleSelector" StyleToUse="{StaticResource myStyle}"/> 
    </Control.Resources> 
</Control>