2012-03-01 59 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>