作者:小天 | 来源:互联网 | 2022-03-18 01:57
需求描述•在ViewModel中处理Model中的数据需要一定时间的等待•ViewModel或Model在获取数据或
需求描述
•在ViewModel中处理Model中的数据需要一定时间的等待
•ViewModel或Model在获取数据或访问同步服务时有一定延迟需要等待
•ViewModel操作View加载数据需要一段时间
解决办法
•显示一个等待UI,当数据处理完毕或服务接口返回后等待UI消失
转动齿轮控件
•参考开源实现SprocketControl :http://wpfspark.codeplex.com/
等待控件
代码如下:
Grid.Column="0"
Margin="0,0,0,0"
HorizOntalAlignment="Center"
VerticalAlignment="Center"
Background="Transparent"
Interval="60"
IsIndeterminate="True"
StartAngle="-90"
TickColor="{DynamicResource MaskForegroundColor}"
TickCount="16"
Tick />
等待效果
定义MVVM中的ViewModel的状态
代码如下:
///
/// 在MVVM模式中ViewModel的状态
///
[Flags]
public enum ViewModelStatus
{
///
/// ViewModel无状态
///
NOne= 0x0,
///
/// ViewModel正在初始化
///
Initializing = 0x1,
///
/// ViewModel初始化完毕
///
Initialized = 0x2,
///
/// ViewModel正在加载
///
Loading = 0x4,
///
/// ViewModel加载完毕
///
Loaded = 0x8,
///
/// ViewModel正在保存
///
Saving = 0x16,
///
/// ViewModel保存完毕
///
Saved = 0x32
}
ViewModel状态转变为控件状态
代码如下:
public class StatusToAnimationVisibilityConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
try
{
string status = value.ToString();
switch (status)
{
case "Initializing":
case "Loading":
case "Saving":
return Visibility.Visible;
case "Loaded":
case "Saved":
default:
return Visibility.Collapsed;
}
}
catch (Exception)
{
return Visibility.Collapsed;
}
}
public object ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
#endregion
}
使UserControl支持异步显示
代码如下:
应用Style至UserControl
代码如下:
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"
d:Design
d:Design
mc:Ignorable="d">
定义基础ViewModel
代码如下:
///
/// 响应式的ViewModel模型
///
public abstract class ViewModelResponsive : ViewModelBase, IViewModelResponsive
{
#region Fields
private ViewModelStatus _status = ViewModelStatus.None;
#endregion
#region ViewModel Status
///
/// 刷新UI数据
///
public virtual void Refresh()
{
}
///
/// ViewModel状态
///
public ViewModelStatus Status
{
get
{
return _status;
}
protected set
{
if (_status != value)
{
_status = value;
RaisePropertyChanged(@"Status");
}
}
}
#endregion
}
ViewModel应用
代码如下:
public class CameraManagementViewModel : ViewModelResponsive
{
protected override void BindCommands()
{
RefreshCommand = new RelayCommand(() =>
{
Refresh();
});
}
public override void Refresh()
{
base.Refresh();
Status = ViewModelStatus.Initializing;
CameraCollection.Clear();
Model.GetCameras(GetCamerasCallback);
}
private void GetCamerasCallback(object sender, AsyncWorkerCallbackEventArgs> args)
{
CameraCollection.Clear();
Status = ViewModelStatus.Loaded;
if (result)
{
foreach (var item in (args.Data as IList))
{
CameraCollection.Add(item);
}
}
}
}