StyleSelector和XAML的返回样式

时间:2012-03-01 16:01:38

标签: wpf styles

我在XAML中创建了一个样式,如何在样式选择器(代码)中返回此样式?

我在XAML中创建了样式,我想只返回在XAML中声明的样式。

3 个答案:

答案 0 :(得分:12)

您可以向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>

答案 1 :(得分:7)

您需要访问存储样式的XAML资源。通常,他们这样做的方法是将其存储在单独的资源文件中。然后,您需要访问该XAML文件的URI作为ResourceDictionary对象。这是一个示例,我使用转换器来决定元素将获得哪种样式。

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 :(得分:2)

如果你只是在寻找一个例子,这里有一个相对有用的例子:

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

如果您有更具体的问题,我建议发布一些代码/ XAML来表明您尝试过的内容以及您遇到的问题。