多値コンバーターを使用できない私たちのために (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;
}
コンバーターは IValueConverter と同様に MarkupExtension から派生しているため、これは WPF コードであることに注意してください。
それが誰かを助けることを願っています、そして再びスティーブンに感謝します!