我有一个具有 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;
但是这是 View
和 ViewModel
之间的紧密耦合。
我也可以通过 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/