c# - 根据 ViewModel 属性更改画笔

标签 c# wpf mvvm mvvm-light fody-propertychanged

我有一个具有 CarViewModel + view (UserControl) 的应用程序。 我想要实现的是当绑定(bind)的DataContext Car.Status 改变时改变画笔的样式。

我找到了如何更改画笔(在 View 后面的代码中):

private void LoadThemeResources(bool isPrepareMode)
{
    if (isPrepareMode)  
    {
        Uri themeUri = new Uri(@"/../Resources/MyBrushes.Light.xaml", UriKind.Relative);
        ResourceDictionary themeDictionary = Application.LoadComponent(themeUri) as ResourceDictionary;
        this.Resources.MergedDictionaries.Add(themeDictionary);
    }
    else
    {
        this.Resources.MergedDictionaries.Clear();
    }
}

默认情况下,应用程序和所有内容都具有分布在多个文件中的深色主题。这个 MyBrushes.Light 会覆盖其中的一些。

但我不知道如何以 MVVM 友好的方式基于 ViewModel 中的属性更改执行 LoadThemeResources 函数。

我可以在 View 后面的代码中执行以下操作:

var vm = (CarViewModel) DataContext;
vm.Car.PropertyChanged += HandleStatusChanged;

但是这是 ViewViewModel 之间的紧密耦合。

我也可以通过 Messenger(来自 MVVM Light)来完成此操作,但这会在整个应用程序中广播,并且看起来有点过分了。

还有别的办法吗?或者首选方式?

最佳答案

我会准备一些附加属性(在UserControl上使用)。将该属性绑定(bind)到您的 View 模型,并在属性更改回调中添加 LoadThemeResources 的代码逻辑,如下所示:

public static class ThemeService {
    public static DependencyProperty IsPrepareModeProperty = 
                  DependencyProperty.RegisterAttached("IsPrepareMode", typeof(bool), typeof(ThemeService), 
                  new PropertyMetadata(isPrepareModeChanged));
    public static bool GetIsPrepareMode(UserControl e){
       return (bool) e.GetValue(IsPrepareModeProperty);
    }
    public static void SetIsPrepareMode(UserControl e, bool value){
       e.SetValue(IsPrepareModeProperty, value);
    }
    static void isPrepareModeChanged(object sender, DependencyPropertyChangedEventArgs e){
       var u = sender as UserControl;
       u.LoadThemeResources((bool)e.NewValue);
    }        
}
//you need some public method of LoadThemeResources
public void LoadThemeResources(bool isPrepareMode) {
     //...
}

XAML 中的用法:

<UserControl ...
             local:ThemeService.IsPrepareMode="{Binding Car.Status}">
      <!-- ... -->
</UserControl>

您还可以为 UserControl 的类声明一个普通的 DependencyProperty 并使用它来代替附加属性(用法是相同的)。

关于c# - 根据 ViewModel 属性更改画笔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33042409/

相关文章:

c# - 在关闭 C# WPF 应用程序之前询问用户

WPF 在 CaptureMouse() 之后不发送 MouseMove 事件;

c# - 一个 ViewModel 中的两个 View (WPF/MVVM)

c# - WPF:Prism 对小型应用程序来说是否过分杀伤力?

c# - kendoui网格全选

c# - Unity - 如何在屏幕覆盖 Canvas 上方显示世界空间 Canvas ?

wpf - 使用 Windows 窗体主机在 WPF 中嵌入 SWF 文件?

c# - 'await response.Content.ReadAsAsync<ReCAPTCHAVerificationResponse>()' 的 .net5 替代品是什么

c# - IMemoryCache 保证唯一的新 key .NET-Core

wpf - 在 MVVM 中的 TextBox.GotFocus() 事件上显示日历