c# - 更改 ModelView 中的样式(MVVM + WPF)

标签 c# wpf xaml mvvm styles

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

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

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

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

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

1) 尝试使用绑定(bind)更改样式(这没有用):

<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 更改样式(这也不起作用。引发异常(Style Trigger to Apply another Style)):

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

最后,我设法通过使用以下代码的组合框解决了这个问题(我只使用组合框来更改 MenuItems 的样式,因此它是不可见的)。从 ( How can I change an elements style at runtime? ) 得到的想法:

<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 的方法,如下所示:

View 模型

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();
    }
}

摘自 Steven Robbins 在 this post 中的回答

关于c# - 更改 ModelView 中的样式(MVVM + WPF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18890099/

相关文章:

c# - 根据 DaysLIST 的值总和获取天数

c# - 我的代码有什么问题 :"clipping polygon(ellipse points) with line segments(subject) with clipper library in c#"

c# - 如何使类实例保持事件状态?

wpf - 在 DataGrid 中捕获 DoubleClick

c# - XAML 序列化 - 需要指定属性

c# - 序列化问题

c# - 剥离后如何从网络上获取图像文件扩展名?

c# - 平滑滚动的垂直文本以获得进度

.net - 如何使用数据绑定(bind)在 WPF 中创建无限深度的 TreeView?

xaml - 滚动浏览页面 Windows Phone 8