WPF Datagrid right align numeric columns - wpf

I'm trying to create a style for the DataGrid cells in my application. I thoight that maybe there is a way to right align the numeric cells in DataGrid using a DataTrigger. Is this even possible?
My style for my DataGrid is this:
<Style TargetType="{x:Type DataGrid}">
<Setter Property="AlternatingRowBackground">
<Setter.Value>
<SolidColorBrush Color="#CCCCCC" />
</Setter.Value>
</Setter>
<Setter Property="CanUserAddRows" Value="False" />
<Setter Property="CanUserDeleteRows" Value="False" />
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Offset="0" Color="#CCCCCC" />
<GradientStop Offset="1" Color="#FFFFFF" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="RowHeaderWidth" Value="0" />
<Setter Property="CellStyle">
<Setter.Value>
<Style TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#7777FF" />
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Setter.Value>
</Setter>
</Style>
I'm thinking of maybe adding some kind of trigger on the CellStyle to detect if the content is numeric (int, double, decimal,...) and style the cell accordingly. Is this possible?
Update
Thinking about this I've tried several things, but it didn't work. I tried using a DataTrigger defined as:
<DataTrigger Binding="{Binding Converter={StaticResource IsNumericConverter}}" Value="True">
<Setter Property="HorizontalContentAlignment" Value="Right" />
</DataTrigger>
Where IsNumericConverter is:
public class IsNumericConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is int || (value is decimal || value is double);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
But when I set a breakpoint on the converter I get that the value is of the type of the whole row, not each individual cell...

One way to do this is to set up the triggers in code-behind. The following method applies a trigger to a DataGridColumn. This trigger uses your IsNumericConverter to determine whether to do the right-alignment:
public static void AddTriggerToColumnStyle(DataGridColumn column)
{
var boundColumn = column as DataGridBoundColumn;
if (boundColumn != null && boundColumn.Binding is Binding)
{
string bindingPropertyPath = (boundColumn.Binding as Binding).Path.Path;
column.CellStyle = new Style()
{
BasedOn = column.CellStyle,
TargetType = typeof(DataGridCell),
Triggers =
{
new DataTrigger
{
Binding = new Binding(bindingPropertyPath) { Converter = new IsNumericConverter() },
Value = true,
Setters =
{
new Setter
{
Property = TextBlock.TextAlignmentProperty,
Value = TextAlignment.Right
}
}
}
}
};
}
}
This method should be safe to call after InitializeComponent() in the code-behind's constructor.
This approach will work if the column has a mixture of numeric and non-numeric data. If the columns contain data of one type only, then this approach will still work, but the triggers created will either never fire or stay fired permanently.
Of course, the above method doesn't have to be repeated in the code-behind for each control that uses DataGrids. You could move it to a static utility class and have all your code-behind classes call this method. You could even add a static utility method that loops through the columns in a DataGrid you pass it and calls the above method for each column.
UPDATE: I modified the above method to allow it deduce the binding property-path. That makes it easier to use. I've also made the method public and static so that it's clear it can be moved to a static utility class.
I did think of another approach, that would run through all of the columns in a DataGrid, inspect the bindings, deduce the type of property bound to and apply the right-alignment to the column. This would avoid creating triggers that never fire or stay permanently fired, and would perhaps fit the case where each column contains data of one type only a bit better. However, this approach would still involve code-behind, it would need to be passed the type that each row would be bound to, and would get complicated if the binding property-paths involved anything more than a single property name.
I'm afraid I can't see a solution to this problem that uses only Styles and avoids code-behind.

I know this is three years old, but I was able to get this done without adding any code to the codebehind and I figured I would share how. using this article as a model: link
It uses multibinding as a way of around your original problem of passing a row to your converter.
add this to your datagrid:
CellStyle="{StaticResource CellRightAlignStyle }"
then add this style to your xaml, you must add it as a resource:
<Window.Resources>
<Style x:Key="CellRightAlignStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="HorizontalAlignment">
<Setter.Value>
<MultiBinding
Converter="{converters:IsNumericConverter}" >
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="Row" Mode="OneWay"/>
</MultiBinding.Bindings>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
Then the converter:
public object Convert(
object[] values,
Type targetType,
object parameter,
CultureInfo culture)
{
if (values[1] is DataRow)
{
//change the text alignment left or right.
var cell = (DataGridCell)values[0];
var row = (DataRow)values[1];
var columnName = cell.Column.SortMemberPath;
if (row[columnName] is int || (row[columnName] is decimal || row[columnName] is double))
return System.Windows.HorizontalAlignment.Right;
}
return System.Windows.HorizontalAlignment.Left;
}
public override object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return null;
}
that is all now your cells that contain numeric data should be right aligned!

I use converter for creating a fixed-length string and monospaced font for view.
Converter:
public class AlignRightConverter : IValueConverter // samples: _10 F2_14 C2_16
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
if (parameter == null) throw new Exception("Format is missing");
var parameterStr = "" + parameter;
if (!parameterStr.Contains('_')) throw new Exception("Unknown format");
var parameterParts = parameterStr.Split('_');
var format = parameterParts[0];
var lengthStr = parameterParts[1];
var length = int.TryParse(lengthStr, out int l) ? l : 12;
if (value == null) return new String(' ', length);
var type = value.GetType();
String targetStr;
if (type == typeof(Double) && format.Length > 0) targetStr = ((Double)value).ToString(format, CultureInfo.GetCultureInfo("ru-ru"));
else
if (type == typeof(Single) && format.Length > 0) targetStr = ((Single)value).ToString(format, CultureInfo.GetCultureInfo("ru-ru"));
else
if (type == typeof(Int32) && format.Length > 0) targetStr = ((Int32)value).ToString(format, CultureInfo.GetCultureInfo("ru-ru"));
else
targetStr = value.ToString();
if (targetStr.Length >= length) return targetStr;
else
return new String(' ', length - targetStr.Length) + targetStr;
}
catch (Exception exception)
{
exception.Log($"Failed convert to string value {value} with parameters {parameter}");
return "" + value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
View:
<DataGridTextColumn Header="Цена покупки" Binding="{Binding Data.CostBuy.Value, Converter={StaticResource AlignRightConverter}, ConverterParameter=C2_16}" FontFamily="Courier New" />
Result:

Related

wpf dynamic user security

The software uses a SmartSnowUser object, which contains a SecurityRole object. The client needs SecurityRole to be customizable, so it has a list of enum SecurityTasks, which the clients can add/remove from. Controls should only be visible if their given SecurityTask exists in the current SmartSnowUser's
SecurityRole.
With this setup, I am struggling to get all the functionality I need.
I need the ability to:
change control visibility based on whether CurrentUser.Role contains GivenTask
make control visibility more granular when necessary (e.g. Visibility &= isInEditMode)
meet the previous two requirements without having to create a separate style for each color/task/extra-qualifier combination
Here are the two main approaches I've tried.
Attempt #1:
Wpf User Security Strategy
Current issue: visibility is not being triggered; breakpoint in Convert() method is never hit
Long-term issue: Uses style, so every other custom style will need to be BasedOn this default; also, have to duplicate functionality for editability
Code:
/**Style.xaml**/
<local:TagToVisibilityConverter x:Key="TagToVisibilityConverter"/>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource TagToVisibilityConverter}">
<Binding Path="MainData.CurrentUser"/>
<Binding RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
/**Style.xaml.cs**/
public class TagToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length >= 2 && (values[1] as FrameworkElement).GetValue(SecurityLevel.RequiredTaskProperty) is SecurityTask requiredTask)
{
//If element has a task assigned and user is not logged in, do not show
if (values[0] is SmartSnowUser currentUser && currentUser.Role != null)
{
return currentUser.Role.Tasks.Contains(requiredTask) ? Visibility.Visible : Visibility.Collapsed;
}
return Visibility.Collapsed;
}
//If element has no task assigned, default to visible
return Visibility.Visible;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class SecurityLevel
{
public static readonly DependencyProperty RequiredTaskProperty = DependencyProperty.RegisterAttached("RequiredTask", typeof(SecurityTask), typeof(FrameworkElement), new PropertyMetadata(SecurityTask.ControlBasic));
public static void SetRequiredTask(UIElement element, SecurityTask value)
{
element.SetValue(RequiredTaskProperty, value);
}
public static SecurityTask GetRequiredTask(UIElement element)
{
return (SecurityTask)element.GetValue(RequiredTaskProperty);
}
}
/**Implementation in User Control**/
<Button Name="BtnNew" Content="Create New Role" Style="{StaticResource ButtonBlue}" server:SecurityLevel.RequiredTask="{x:Static enums:SecurityTask.EditRoles}" />
Attempt #2:
How to extend instead of overriding WPF Styles
How to add dependency property to FrameworkElement driven classes in WPF?
Attempted to merge these two solutions into one. Set the Tag value to a SecurityTask, then use trigger to set visibility
issue: cannot set visibility at a more granular level without a style (e.g. cannot set 'Visibility' property directly in control); cannot distinguish between visibility/editability
Code:
/**Style.xaml**/
<!--#region Visibility-->
<!-- Default frameworkElement style definition -->
<local:TagToVisibilityConverter x:Key="TagToVisibilityConverter"/>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource TagToVisibilityConverter}">
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
<Binding Path="MainData.CurrentUser"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
<!-- Extending default style -->
<Style x:Key="ButtonBasic" TargetType="Button" BasedOn="{StaticResource {x:Type FrameworkElement}}">
<Setter Property="Background" Value="{StaticResource BrushGreyDark}" />
<Setter Property="Foreground" Value="{StaticResource BrushWhite}" />
</Style>
<Style x:Key="ButtonBlue" TargetType="Button" BasedOn="{StaticResource ButtonBasic}">
<Setter Property="Background" Value="{StaticResource BrushBlue}" />
</Style>
/**Style.xaml.cs**/
public class TagToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values.Length >= 2 && values[0] is SecurityTask requiredTask)
{
//If element has a task assigned and user is not logged in, do not show
if (values[1] is SmartSnowUser currentUser && currentUser.Role != null)
{
return currentUser.Role.Tasks.Contains(requiredTask) ? Visibility.Visible : Visibility.Collapsed;
}
return Visibility.Collapsed;
}
//If element has no task assigned, default to visible
return Visibility.Visible;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
/**Implementation in User Control**/
//This button works great. Exactly what I need.
<Button Name="BtnNew" Content="Create New Role" Style="{StaticResource ButtonBlue}" Tag="{x:Static enums:SecurityTask.EditRoles}" />
//This button does not work, because the newly set Visibility property overrides the style.
<Button Name="BtnEdit" Content="Edit Role" Style="{StaticResource ButtonBlue}" Tag="{x:Static enums:SecurityTask.EditRoles}" Visibility="{Binding IsEditMode, Converter={StaticResource InverseBoolToVisibilityConverter}}" />
Attempt #2 ALMOST works. It's that last stinking button, BtnEdit. It is far too cluttered to create a new style - BasedOn ButtonBlue, which is BasedOn ButtonDefault, which is BasedOn our original up there - every time I need to add another qualifier to my visibility setting.
I seem to be over-complicating this. Is there a cleaner approach to what I'm trying to do?

How Do I Bind to Key in Dictionary only if it exists

I have a case where I dont know if a key exists in a dictionary, but if it does. I want to bind to it.
In this case, its a colour, so I use a converter to convert the colour and bind. This works great but only if the key exists!
I cant think of a way to setup a trigger, which checks if the key exists before I execute the binding?
Note in the code below, fieldColour may or may not exist. I would like to setup a data trigger which I can do, but I dont know how this is going to be possible.
<ToggleButton.Style>
<Style>
<Setter Property="ToggleButton.Background" Value="{Binding Path=Schema.KeyValues[fieldColour], Converter={converters:Converter_StringToColour}}" />
</Style>
</ToggleButton.Style>
I eventually worked out the best way. You can pass it to a converter and let that decide if the parameter is null:
C#
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null) return null;
if (value == null) return null;
string key = (parameter as string).ToLower();
Dictionary<string, string> dict = value as Dictionary<string, string>;
if (!dict.ContainsKey(key)) return null;
string colour = dict[key];
var converter = TypeDescriptor.GetConverter(typeof(Color));
if (converter.IsValid(colour))
{
//Easter Egg.
if (colour == "Magenta")
{
ErrorConsoleViewModel.Instance.LogWarning("Magenta? Really? Are you trying to blind me!");
}
Color newCol = (Color)converter.ConvertFromString(colour);
return new SolidColorBrush(newCol);
}
ErrorConsoleViewModel.Instance.LogWarning("Colour " + colour + " not found. See C# Colour Table: http://www.dotnetperls.com/color-table");
return null;
}
XAML
<Style>
<Setter Property="ToggleButton.Background" Value="{Binding Path=Schema.KeyValues, Converter={converters:Converter_DictionaryStringToColour}, ConverterParameter='fieldColour'}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Schema.KeyValues, Converter={converters:Converter_DictionaryStringToColour}, ConverterParameter='fieldColour'}" Value="{x:Null}">
<Setter Property="ToggleButton.Background" Value="#A9C7F0" />
</DataTrigger>
</Style.Triggers>
</Style>

Colouring a hierarchical XamDataGrid

I'm using a XamDataGrid (Infragistics-control) to display some hierarchical data. The objects that I can have up to 10 levels and I need to be able to give each level a specific background-color. I use the AssigningFieldLayoutToItem-event to get the "level" of the item and it would be best to assign the background/style here as well, I suppose.
I have tried specifying a DataRecordCellArea-style and even a CellValuePresenter-style but I can't get any of these to work with the FieldLayouts.
Another solution is to write a FieldLayout for each level, but this would create a lot of unnecessary XAML-code.
Any suggestions as to what I should do?
If you have a different FieldLayout for each level, you could use a single style targeting the DataRecordPresenter with a converter to set the background.
XAML:
<local:BackgroundConverter x:Key="BackgroundConverter"/>
<Style TargetType="{x:Type igDP:DataRecordPresenter}">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=FieldLayout.Key, Converter={StaticResource BackgroundConverter}}"/>
</Style>
Converter:
public class BackgroundConverter:IValueConverter
{
public BackgroundConverter()
{
this.Brushes = new Dictionary<string, Brush>();
}
public Dictionary<string, Brush> Brushes {get;set;}
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
{
string key = value.ToString();
if (this.Brushes.ContainsKey(key))
return this.Brushes[value.ToString()];
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
The following will set the colors to use for fields with Key1 and Key2:
BackgroundConverter backgroundConverter = this.Resources["BackgroundConverter"] as BackgroundConverter;
backgroundConverter.Brushes.Add("Key1", Brushes.Green);
backgroundConverter.Brushes.Add("Key2", Brushes.Yellow);
If you are reusing the same FieldLayout for multiple fields, then you could use the InitializeRecord event and change the style to bind to the Tag of the DataRecord like this:
XAML:
<Style TargetType="{x:Type igDP:DataRecordPresenter}">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Record.Tag}"/>
</Style>
C#:
void XamDataGrid1_InitializeRecord(object sender, Infragistics.Windows.DataPresenter.Events.InitializeRecordEventArgs e)
{
if (!e.ReInitialize)
{
// Set the tag to the desired brush.
e.Record.Tag = Brushes.Blue;
}
}
Note that I didn't add the conditional logic for determining the brush to use and that still needs to be done for different levels to have different backgrounds.

wpf - datatriggers repeated use

I have the current DataTrigger:
<DataTrigger Binding="{Binding HeaderType}" Value="1">
<Setter Property="BorderThickness" Value="5"/></DataTrigger>
I want to do the same with values 2-100
Do I have to copy the Data Trigger 99 times or maybe there's a better way ?
Add a property to your view model:
public bool HasImportantHeader // or something...
{
get { return HeaderType >=1 && HeaderType <= 100; }
}
Use that property in the data trigger:
<DataTrigger Binding="{Binding HasImportantHeader}" Value="True">
<Setter Property="BorderThickness" Value="5"/>
</DataTrigger>
Generally, I like to keep my XAML as simple as possible, put all the logic in the view model, and avoid using Converters unless they are absolutely necessary.
Let's say you add another view, where you want to use bold text to indicate the header type is between 1 and 100. Just re-use the HasImportantHeader property, something like:
<DataTrigger Binding="{Binding HasImportantHeader}" Value="True">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
Later, you may decide that all header types up to 200 should have thick border and bold text. It'll be a simple matter of changing the implementation of the HasImportantHeader property.
I've used this in similar situations
<DataTrigger Binding="{Binding HeaderType,
Converter={StaticResource RangeConverter},
ConverterParameter=1-100}"
Value="True">
<Setter Property="BorderThickness" Value="5"/>
</DataTrigger>
And in the converter we return true or false depending on the ranges
public class RangeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string[] ranges = parameter.ToString().Split(new char[]{'-'});
int headerType = (int)value;
if (headerType >= System.Convert.ToInt32(ranges[0]) &&
headerType <= System.Convert.ToInt32(ranges[1]))
{
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
You need to use a converter for that purpose.You can add a converter on your DataTrigger.
The Converter will allow you to pass in the value, and return true or false.
<DataTrigger
Binding="{Binding HeaderType, Converter={StaticResource RengeConvertor}}"
Value="true"
>
<Setter Property="BorderThickness" Value="5" />
</DataTrigger>
and your converter should look something like
public class RengeConvertor : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int data = (int)value;
if (data >= 2 && data <= 100)
return true;
else
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
You may also find this interesting http://zamjad.wordpress.com/2010/07/29/range-converter/

Binding for WPF Styles

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.
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>
<MultiBinding Converter="{StaticResource StyleConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="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:
class StyleConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FrameworkElement targetElement = values[0] as FrameworkElement;
string styleName = values[1] as string;
if (styleName == null)
return null;
Style newStyle = (Style)targetElement.TryFindResource(styleName);
if (newStyle == null)
newStyle = (Style)targetElement.TryFindResource("MyDefaultStyleName");
return newStyle;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
It's not something I do very often, but that should work from memory :)
It seems that you need to use DataTrigger class. It allows you to apply different styles to your button based on it's content.
For example following style will change button's background property to red based on value of data context object's property
<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path="Some property"}"
Value="some property value">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
For those of us who can't use multi value converter (I'm looking at you SL4 and WP7:), thanks to Steven's answer I found a way using an ordinary value converter.
The only assumption is the style value is contained within the property of the style being set.
So if you're using the MVVM pattern then the style value (such as TextSmall, TextMedium, TextLarge) is assumed to be part of the view model, and all you have to do is pass the converter parameter defining the name of style.
For example, say your view model has property:
public string ProjectNameStyle
{
get { return string.Format("ProjectNameStyle{0}", _displaySize.ToString()); }
}
Application style:
<Application.Resources>
<Style x:Key="ProjectNameStyleSmall" TargetType="TextBlock">
<Setter Property="FontSize" Value="40" />
</Style>
<Style x:Key="ProjectNameStyleMedium" TargetType="TextBlock">
<Setter Property="FontSize" Value="64" />
</Style>
<Style x:Key="ProjectNameStyleLarge" TargetType="TextBlock">
<Setter Property="FontSize" Value="90" />
</Style>
XAML view:
<TextBlock
Text="{Binding Name}"
Style="{Binding ., Mode=OneWay, Converter={cv:StyleConverter}, ConverterParameter=ProjectNameStyle}">
With your StyleConverter class implementing IValueConverter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(Style))
{
throw new InvalidOperationException("The target must be a Style");
}
var styleProperty = parameter as string;
if (value == null || styleProperty == null)
{
return null;
}
string styleValue = value.GetType()
.GetProperty(styleProperty)
.GetValue(value, null)
.ToString();
if (styleValue == null)
{
return null;
}
Style newStyle = (Style)Application.Current.TryFindResource(styleValue);
return newStyle;
}
Note that this is WPF code, as the converter is derived from a MarkupExtension as well as IValueConverter, but it will work in SL4 and WP7 if you use static resource and add a bit more leg work as the TryFindResource method doesn't exist.
Hope that helps someone, and thanks again Steven!
ViewModel
private Style _dynamicStyle = (Style)Application.Current.FindResource("Style1");
public Style DynamicStyle
{
get { return _dynamicStyle; }
set
{
_dynamicStyle = value;
OnPropertyChanged("DynamicStyle");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Implement a property in your ViewModel and then dynamically change style where ever you want like below.
DynamicStyle=(Style)Application.Current.FindResource("Style2");// you can place this code where the action get fired
View
Then set DataContext value and then implement the following code in your view
<Button Style="{Binding DynamicStyle,Mode=TwoWay}"/>

Resources