I'm trying to create a custom control – a button – which will have multiple styles applied to it depending on the value of a property within the data context.
What I was thinking is using something similar to:
<Button Style="{Binding Path=ButtonStyleProperty, Converter={StaticResource styleConverter}}" Text="{Binding Path=TextProp}" />
And in code… Implement an IValueConverter which does something similar to the code below in the ConvertTo
method:
switch(value as ValueEnums)
{
case ValueEnums.Enum1:
FindResource("Enum1ButtonStyle") as Style;
break;
... and so on.
}
However I'm not entirely sure about how to pull out the style object and even if this is possible at all…
What I am doing in the mean time is handling the DataContextChanged
event, then attaching a handler to the PropertyChanged
event of the object being bound to the button – then running the switch statement in there.
Its not quite perfect but until I can find a better solution it seems like that is what I'll have to use.
Best Answer
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:
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:
It's not something I do very often, but that should work from memory :)