对于我们这些不能使用多值转换器的人(我在看你 SL4 和 WP7 :),感谢 Steven 的回答,我找到了一种使用普通值转换器的方法。
唯一的假设是样式值包含在所设置样式的属性中。
因此,如果您使用 MVVM 模式,那么样式值(例如 TextSmall、TextMedium、TextLarge)被假定为视图模型的一部分,您所要做的就是传递定义样式名称的转换器参数。
例如,假设您的视图模型具有属性:
public string ProjectNameStyle
{
get { return string.Format("ProjectNameStyle{0}", _displaySize.ToString()); }
}
申请风格:
<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 视图:
<TextBlock
Text="{Binding Name}"
Style="{Binding ., Mode=OneWay, Converter={cv:StyleConverter}, ConverterParameter=ProjectNameStyle}">
使用实现 IValueConverter 的 StyleConverter 类:
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;
}
请注意,这是 WPF 代码,因为转换器是从 MarkupExtension 和 IValueConverter 派生的,但如果您使用静态资源并添加更多的腿部工作,因为 TryFindResource 方法不存在,它将在 SL4 和 WP7 中工作。
希望对某人有所帮助,再次感谢史蒂文!