Wpf 从MVVM更改DynamicSource
我正在尝试将DynamicSource值绑定到viewmodel中的公共属性,然后对其进行操作。静态资源基本上是显示一个图像。有什么建议吗,谢谢Wpf 从MVVM更改DynamicSource,wpf,xaml,mvvm,Wpf,Xaml,Mvvm,我正在尝试将DynamicSource值绑定到viewmodel中的公共属性,然后对其进行操作。静态资源基本上是显示一个图像。有什么建议吗,谢谢 <Rectangle Width="20" Height="20"> <Rectangle.Fill> <VisualBrush Stretch="Fill" Visual="{StaticResource appbar_page_number1}" /> </Recta
<Rectangle Width="20" Height="20">
<Rectangle.Fill>
<VisualBrush Stretch="Fill" Visual="{StaticResource appbar_page_number1}" />
</Rectangle.Fill>
</Rectangle>
如果您有固定数量的资源,并且希望将枚举转换为资源,则可以使用绑定转换器。大概是这样的:
public enum PossibleValue
{
Value1,
Value2,
Value3,
Value4
}
转换器的外观如下所示:
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();
}
}
您可以在参考资料部分声明转换器:
<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}"/>
现在,将您的矩形与VM中的属性链接(让我们将此属性称为MightyProperty)
这样,每次视图模型中的MightyProperty发生更改时,转换器都会找到相应的视觉对象,并将其发送到VisualBrush的视觉属性
当然,MightyProperty不必是枚举类型,它可以是int、字符串或任何其他类型。您只需调整Convert方法中的代码以匹配您的类型。您好,我有3个资源(appbar\u page\u number1、appbar\u page\u number2、appbar\u page\u number3)。我不确定如何使用我的属性设置这些资源。理想情况下,我会将appbar\u page\u number1绑定到一个属性,然后将该属性更改为number1、2等值。我在响应中添加了一些解释。
<Rectangle Width="20" Height="20">
<Rectangle.Fill>
<VisualBrush Stretch="Fill" Visual="{Binding MightyProperty, Converter={StaticResource myConverter}}" />
</Rectangle.Fill>
</Rectangle>