这是一个示例,介绍如何设置一个视图,在ViewModel/Model正在处理长时间任务时显示“加载”界面。
窗口
<Window x:Class="Loading.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:Loading"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:VisibilityConverter x:Key="visibilityConverter" />
</Window.Resources>
<Window.DataContext>
<local:ViewModel x:Name="viewModel" />
</Window.DataContext>
<Grid>
<Button Content="Perform" VerticalAlignment="Bottom" HorizontalAlignment="Center" Width="100" Height="30" Command="{Binding HandleRequestCommand}" />
<Border Visibility="{Binding Path=IsLoading,Converter={StaticResource visibilityConverter}}" Background="#AAAAAAAA" Margin="5">
<TextBlock Text="Loading..." VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</Grid>
VisibilityConverter.cs(简单的帮助转换器)
class VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool isLoading;
public ViewModel()
{
HandleRequestCommand = new Command(HandleRequest);
}
public bool IsLoading
{
get
{
return isLoading;
}
set
{
if (value != isLoading)
{
isLoading = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsLoading)));
}
}
}
public ICommand HandleRequestCommand
{
get;
}
public void HandleRequest()
{
IsLoading = true;
Task.Factory.StartNew(LongRunningOperation);
}
private void LongRunningOperation()
{
Dispatcher.CurrentDispatcher.Invoke(() => IsLoading = false);
}
}