Binding for WPF Styles

http://stackoverflow.com/questions/410579/binding-for-wpf-styles

 If you want to replace the whole style (rather than just elements of it) then you'll probably be storing those styles in resources. You should be able to do something along the lines of:

<Button>
   
<Button.Style>
       
<MultiBindingConverter="{StaticResource StyleConverter}">
           
<MultiBinding.Bindings>
               
<BindingRelativeSource="{RelativeSource Self}"/>
               
<BindingPath="MyStyleString"/>
           
</MultiBinding.Bindings>
       
</MultiBinding>
   
</Button.Style>
</Button>

By using a MultiBinding and using Self as the first binding we can then lookup resources in our converter. The converter needs to implement IMultiValueConverter (rather than IValueConverter) and can look something like this:

classStyleConverter:IMultiValueConverter 
{
   
publicobjectConvert(object[] values,Type targetType,object parameter,System.Globalization.CultureInfo culture)
   
{
       
FrameworkElement targetElement = values[0]asFrameworkElement;
       
string styleName = values[1]asstring;

       
if(styleName ==null)
           
returnnull;

       
Style newStyle =(Style)targetElement.TryFindResource(styleName);

       
if(newStyle ==null)
            newStyle
=(Style)targetElement.TryFindResource("MyDefaultStyleName");

       
return newStyle;
   
}

   
publicobject[]ConvertBack(object value,Type[] targetTypes,object parameter,System.Globalization.CultureInfo culture)
   
{
       
thrownewNotImplementedException();
   
}
}

It's not something I do very often, but that should work from memory :)

原文地址:https://www.cnblogs.com/xxz526/p/2944857.html