我有一个具有CarViewModel + view(UserControl)的应用程序. 我想要实现的是在绑定的DataContext Car.Status更改时更改画笔的样式.
I have an application which has CarViewModel + view (UserControl). What I want to achieve is to change the style of brushes when the bound DataContext Car.Status changes.
我发现了如何更改画笔(在视图后面的代码中):
I found out how to change the brushes (in code behind of the 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覆盖其中一些.
By default the application and everthing has a dark theme spread over multiple files. This MyBrushes.Light overwrites some of those.
但是我不知道如何以MVVM友好的方式基于ViewModel中的属性更改执行LoadThemeResources函数.
But I have no clue how I can execute the LoadThemeResources function based on a property change in the ViewModel in a MVVM friendly way.
我可以在视图背后的代码中完成
I can do in the code behind of the view:
var vm = (CarViewModel) DataContext; vm.Car.PropertyChanged += HandleStatusChanged;但这是View和ViewModel之间的紧密耦合.
But this is a tight coupling between View and ViewModel.
我也可以通过Messenger(来自MVVM Light)来做到这一点,但这在整个应用程序中都被广播了,而且似乎有些过分.
I can also do it via Messenger (From MVVM Light), but that gets broadcasted throughout the whole application and seems overkill.
还有其他方法吗?还是首选方式?
Is there an other way? Or preferred way?
推荐答案我将准备一些附加属性(在UserControl上使用).将该属性绑定到您的视图模型,并在更改后的属性回调中添加LoadThemeResources的代码逻辑,如下所示:
I would prepare some attached property (used on UserControl). Bind that property to your view-model and add code logic of LoadThemeResources in the property changed callback, something like this:
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中的使用 :
Usage in XAML:
<UserControl ... local:ThemeService.IsPrepareMode="{Binding Car.Status}"> <!-- ... --> </UserControl>您还可以为UserControl的类声明一个普通的DependencyProperty,并使用它代替附加的属性(用法是相同的).
You can also declare a normal DependencyProperty for your UserControl's class and use that instead of the attached property (the usage is just the same).
更多推荐
根据ViewModel属性更改画笔
发布评论