在模型视图 (MVVM + WPF) 中更改样式

本文关键字:样式 WPF 模型 视图 MVVM | 更新日期: 2023-09-27 18:31:51

我有一个使用 MVVM 模式(MVVM Light Toolkit)在 WPF 中开发的应用程序。

到目前为止,我没有任何问题,直到在运行时更改与我的一些控件(一组 MenuItems)关联的样式。(它们最多可以有三种不同的样式)。

如果我不使用 MVVM,我可以使用以下命令解决它:

MenuElement_Left4.Style = (Style)FindResource("MenuButtonTabsLeft");

但是因为我想完全在 MVVM 中做到这一点,所以我做了这些测试来实现这一点:

1)尝试使用绑定更改样式(这不起作用):

<MenuItem x:Name="MenuElement_Left4" Header="Test" Style="{Binding SelectedStyle}">

在视图模型中:

public string SelectedStyle
    {
       get { return this.selectedStyle; }
       set { this.selectedStyle = value; 
             RaisePropertyChanged("SelectedStyle");
           }
    }
    private string selectedStyle;

2)使用数据触发器更改样式(这也不起作用。引发异常(样式触发器以应用其他样式)):

<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>

在我的视图中模型:

public int AvailableStylesIndex
{
    get { return this.availableStylesIndex; }
    set
    {
        this.availableStylesIndex = value;
        RaisePropertyChanged("AvailableStylesIndex");
    }
}

我宁愿使用更清洁的方式。有什么建议吗?一段代码将非常有帮助。

在模型视图 (MVVM + WPF) 中更改样式

由于您将样式保留在资源中,因此更简洁的方法是使用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();
    }
}

摘自史蒂文·罗宾斯在这篇文章中的回答