我在VS2017中创建了一个新的WPF项目,并通过NuGet导入了MVVM Light。
然后我添加了一些代码,每25毫秒应该从MainWindows网格改变背景颜色。可悲的是,这种变化并没有传播,我也不知道它为什么不更新。也许这里有人可以帮助我。
这是代码:
MainViewModel.cs
using GalaSoft.MvvmLight;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace Strober.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ObservableObject
{
private DispatcherTimer timer;
public string Title { get; set; }
private Brush _background;
public Brush Background
{
get
{
return _background;
}
set
{
_background = value;
OnPropertyChanged("Background");
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Background = new SolidColorBrush(Colors.Black);
timer = new DispatcherTimer();
timer.Tick += Timer_Tick;
timer.Interval = new TimeSpan(0, 0, 0,0,100);
timer.Start();
}
private void Timer_Tick(object sender, System.EventArgs e)
{
if (Background == Brushes.Black)
{
Background = new SolidColorBrush(Colors.White);
Title = "White";
}
else
{
Background = new SolidColorBrush(Colors.Black);
Title = "Black";
}
}
#region INotifiedProperty Block
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string PropertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
#endregion
}
}
ViewModelLocator.cs
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocator xmlns:vm="clr-namespace:Strober"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
You can also use Blend to do all this with the tool's support.
See http://www.galasoft.ch/mvvm
*/
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using CommonServiceLocator;
namespace Strober.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
////if (ViewModelBase.IsInDesignModeStatic)
////{
//// // Create design time view services and models
//// SimpleIoc.Default.Register<IDataService, DesignDataService>();
////}
////else
////{
//// // Create run time view services and models
//// SimpleIoc.Default.Register<IDataService, DataService>();
////}
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
}
MainWindow.xaml(MainWindow.xaml.cs只是定期生成的文件)
<Window x:Class="Strober.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Strober"
mc:Ignorable="d"
DataContext="{Binding Main, Source={StaticResource Locator}}"
Title="{Binding Title}" Height="450" Width="800">
<Grid Background="{Binding Background}">
</Grid>
</Window>
App.xaml中
<Application x:Class="Strober.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Strober" StartupUri="MainWindow.xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:Strober.ViewModel" />
</ResourceDictionary>
</Application.Resources>
</Application>
格雷格
你的代码中的主要问题是System.Windows.Media.SolidColorBrush
没有覆盖Equals()
方法,因此你的表达式Background == Brushes.Black
永远不会是true
。由于您正在创建SolidColorBrush
对象的显式新实例,并且由于==
运算符只是比较实例引用,因此刷子值与内置Brushes.Black
实例之间的比较总是失败。
修复代码的最简单方法是使用实际的Brushes
实例:
private void Timer_Tick(object sender, System.EventArgs e)
{
if (Background == Brushes.Black)
{
Background = Brushes.White;
Title = "White";
}
else
{
Background = Brushes.Black;
Title = "Black";
}
}
然后,当您比较实例引用时,它们实际上是可比较的,您将根据需要检测“黑色”条件。
我会注意到,因为你也没有提高PropertyChanged
来改变Title
属性,所以这种绑定也不会按预期工作。
对于它的价值,我会完全避免你的设计。首先,查看模型对象应避免使用特定于UI的类型。当然,这将包括Brush
类型。可以说,它还包括DispatcherTimer
,因为它存在于UI的服务中。除此之外,DispatcherTimer
是一个相对不精确的计时器,虽然它主要存在一个计时器,它在拥有计时器的调度程序线程上引发其Tick
事件,因为WPF自动将属性更改事件从任何其他线程编组到UI线程,它在这个例子中并没有那么有用。
以下是您的程序版本,IMHO更符合典型的WPF编程实践:
class MainViewModel : NotifyPropertyChangedBase
{
private string _title;
public string Title
{
get { return _title; }
set { _UpdateField(ref _title, value); }
}
private bool _isBlack;
public bool IsBlack
{
get { return _isBlack; }
set { _UpdateField(ref _isBlack, value, _OnIsBlackChanged); }
}
private void _OnIsBlackChanged(bool obj)
{
Title = IsBlack ? "Black" : "White";
}
public MainViewModel()
{
IsBlack = true;
_ToggleIsBlack(); // fire and forget
}
private async void _ToggleIsBlack()
{
while (true)
{
await Task.Delay(TimeSpan.FromMilliseconds(100));
IsBlack = !IsBlack;
}
}
}
此视图模型类使用我用于所有视图模型的基类,因此我不必一直重新实现INotifyPropertyChanged
:
class NotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void _UpdateField<T>(ref T field, T newValue,
Action<T> onChangedCallback = null,
[CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
{
return;
}
T oldValue = field;
field = newValue;
onChangedCallback?.Invoke(oldValue);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
您会注意到视图模型类没有任何特定于UI的行为。它可以与任何程序,WPF或其他程序一起使用,只要该程序有办法对PropertyChanged
事件作出反应,并使用视图模型中的值。
为了使这项工作,XAML变得更加冗长:
<Window x:Class="TestSO55437213TimerBackgroundColor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:p="http://schemas.microsoft.com/netfx/2007/xaml/presentation"
xmlns:l="clr-namespace:TestSO55437213TimerBackgroundColor"
mc:Ignorable="d"
Title="{Binding Title}" Height="450" Width="800">
<Window.DataContext>
<l:MainViewModel/>
</Window.DataContext>
<Grid>
<Grid.Style>
<p:Style TargetType="Grid">
<Setter Property="Background" Value="White"/>
<p:Style.Triggers>
<DataTrigger Binding="{Binding IsBlack}" Value="True">
<Setter Property="Background" Value="Black"/>
</DataTrigger>
</p:Style.Triggers>
</p:Style>
</Grid.Style>
</Grid>
</Window>
(注意:我已明确命名http://schemas.microsoft.com/netfx/2007/xaml/presentation XML命名空间,与<Style/>
元素一起使用,仅作为Stack Overflow不充分的XML标记处理的解决方法,否则将无法将<Style/>
元素识别为实际的XML元素。在您自己的程序,你可以随意离开。)
这里的关键是UI关注的整个处理在UI声明本身。视图模型不需要知道UI如何表示黑色或白色。它只是切换一面旗帜。然后UI监视该标志,并根据其当前值适当地应用属性设置器。
最后,我会注意到,对于像这样在UI中反复改变状态,另一种方法是使用WPF的动画功能。这超出了这个答案的范围,但我鼓励你阅读它。这样做的一个优点是动画使用比我上面使用的基于线程池的Task.Delay()
方法更高分辨率的计时模型,因此通常会提供更平滑的动画(当然,当你的间隔变得越来越小时 - 如你的帖子表明你打算使用25毫秒 - 无论如何你都无法让WPF顺利保持;在某些时候,你会发现像WinForms,WPF,Xamarin等更高级别的UI框架就可以了不会在如此精细的计时器级别上运行。