Reputation: 323
I created a style in XAML, How Can I return this style in style selector (code)?
I created style in XAML and I want to only return the style which is declared in XAML.
Upvotes: 4
Views: 14591
Reputation: 680
You can add a property to your StyleSelector
and then use the property to pass a reference to the Style
in XAML.
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>
Upvotes: 12
Reputation: 2769
You need to access the XAML resource where you stored the style. Generally they way to do this is store it in a seperate resources file. Then you need to access the URI of that XAML file as a ResourceDictionary object. Here is an example where I use a converter to decide which style an element will get.
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();
}
}
}
Upvotes: 8
Reputation: 6090
If you're just looking for an example, here's a relatively usable one:
http://www.shujaat.net/2010/10/wpf-style-selector-for-items-in.html
If you have more specific questions, I would suggest posting some code/XAML to indicate what you've tried and what problems you're having.
Upvotes: 2