我有一个使用 MVVM 模式(MVVM Light Toolkit)在 WPF 中开发的应用程序。
到目前为止,我没有遇到任何问题,直到需要在运行时更改与我的一些控件(一组菜单项)关联的样式。 (它们最多可以有三种不同的样式)。
如果我没有使用 MVVM,我可以使用以下命令解决它:
MenuElement_Left4.Style = (Style)FindResource("MenuButtonTabsLeft");
但是因为我想完全在 MVVM 中完成它,所以我做了这些测试来实现这一点:
1)尝试使用绑定更改样式(这不起作用):
<MenuItem x:Name="MenuElement_Left4" Header="Test" Style="{Binding SelectedStyle}">
在 ViewModel 中:
public string SelectedStyle
{
get { return this.selectedStyle; }
set { this.selectedStyle = value;
RaisePropertyChanged("SelectedStyle");
}
}
private string selectedStyle;
2)使用 DataTrigger 更改样式(这也不起作用。引发异常(样式触发器应用另一种样式)):
<MenuItem.Style>
<Style TargetType="{x:Type MenuItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=TestStyle}" Value="True">
<Setter Property="Style" Value="{StaticResource MenuButtonTabsLeftArrow}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=TestStyle}" Value="False">
<Setter Property="Style" Value="{StaticResource MenuButtonTabsLeft}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.Style>
最后,我设法使用 Combox 使用以下代码解决了这个问题(我只使用 ComboBox 来更改 MenuItems 的样式,因此它是不可见的)。这个想法来自(如何在运行时更改元素样式?):
<MenuItem x:Name="MenuElement_Left4" Header="Test" Style="{Binding ElementName=AvailableStyles, Path=SelectedItem.Tag}">
<ComboBox Name="AvailableStyles" SelectedIndex="{Binding AvailableStylesIndex}" Visibility="Collapsed">
<ComboBoxItem Tag="{x:Null}">None</ComboBoxItem>
<ComboBoxItem Tag="{StaticResource MenuButtonTabsLeftArrow}">MenuButtonTabsLeftArrow</ComboBoxItem>
<ComboBoxItem Tag="{StaticResource MenuButtonTabsLeft}">MenuButtonTabsLeft</ComboBoxItem>
</ComboBox>
在我的 ViewModel 中:
public int AvailableStylesIndex
{
get { return this.availableStylesIndex; }
set
{
this.availableStylesIndex = value;
RaisePropertyChanged("AvailableStylesIndex");
}
}
我宁愿使用更干净的方式。有什么建议么?一段代码会非常有帮助。
由于您将样式保留在资源中,因此更简洁的方法是使用 IMultiValueConverter 的第一个方法,如下所示:
视图模型
public string SelectedStyle
{
get { return this.selectedStyle; }
set { this.selectedStyle = value;
RaisePropertyChanged("SelectedStyle");
}
}
private string selectedStyle;
Xaml:
<MenuItem.Style>
<MultiBinding Converter="{StaticResource StyleConverter}">
<MultiBinding.Bindings>
<Binding RelativeSource="{RelativeSource Self}"/>
<Binding Path="SelectedStyle"/>
</MultiBinding.Bindings>
</MultiBinding>
</MenuItem.Style/>
在转换器中找到您想要的样式并应用它
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();
}
}
摘自史蒂文·罗宾斯在这篇文章中的回答