Reputation: 2828
I am trying to bind DynamicResource value to a public property located in viewmodel and manipulate it afterwards. The static resource is showing basically an image. Any suggestions, thanks.
<Rectangle Width="20" Height="20">
<Rectangle.Fill>
<VisualBrush Stretch="Fill" Visual="{StaticResource appbar_page_number1}" />
</Rectangle.Fill>
</Rectangle>
Upvotes: 1
Views: 1112
Reputation: 2062
If you have a fixed number of resources and you want to convert lets say an enum to a resource then you can use a binding converter. Something like this:
public enum PossibleValue
{
Value1,
Value2,
Value3,
Value4
}
The converter would look like:
public class EnumToVisualConverter : IValueConverter
{
public Visual Visual1 { get; set; }
public Visual Visual2 { get; set; }
public Visual Visual3 { get; set; }
public Visual Visual4 { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is PossibleValue))
return null; //Or a some default Visual
PossibleValue val = (PossibleValue)value;
switch (val)
{
case PossibleValue.Value1:
return Visual1;
case PossibleValue.Value2:
return Visual2;
case PossibleValue.Value3:
return Visual3;
default:
return Visual4;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And you declare the converter in resources section :
<l:EnumToVisualConverter x:Key="myConverter"
Visual1="{StaticResource appbar_page_number1}"
Visual2="{StaticResource appbar_page_number2}"
Visual3="{StaticResource appbar_page_number3}"
Visual4="{StaticResource appbar_page_number4}"/>
Now to link your rectangle with the property in your VM (let's call this property MightyProperty).
<Rectangle Width="20" Height="20">
<Rectangle.Fill>
<VisualBrush Stretch="Fill" Visual="{Binding MightyProperty, Converter={StaticResource myConverter}}" />
</Rectangle.Fill>
</Rectangle>
In this way each time MightyProperty will change in your View Model the converter will find the appropriate visual and send it to the Visual property of the VisualBrush.
Of course MightyProperty don't have to be of Enum type it can be an int a string or any other type. You will only have to adapt the code inside Convert method to match your type.
Upvotes: 2