从另一个线程更新网格的可见性

时间:2013-11-24 09:19:23

标签: c# wpf multithreading xaml

问题:

我有以下课程:

1)SMServiceClient - RestSharp上的包装

public class SMServiceClient
{
    public delegate void AuthorizationSucceededHandler(SMServiceEventArgs args);
    public event AuthorizationSucceededHandler AuthorizationSucceeded;

    public delegate void AuthorizationFailedHandler(SMServiceEventArgs args);
    public event AuthorizationFailedHandler AuthorizationFailed;

    public delegate void RequestStartedHandler(SMServiceEventArgs args);
    public event RequestStartedHandler RequestStarted;

    public delegate void RequestFinishedHandler(SMServiceEventArgs args);
    public event RequestFinishedHandler RequestFinished;


    private const string baseUrl = "http://10.0.0.6:4000";
    private RestClient client;

    public SMServiceClient()
    {
        client = new RestClient(baseUrl);
        client.CookieContainer = new CookieContainer();
        client.FollowRedirects = false;
    }

    public void AuthUser(string username, string password)
    {
        RequestStarted(new SMServiceEventArgs());
        var request = new RestRequest("/api/login", Method.POST);
        request.AddParameter("username", username);
        request.AddParameter("password", password);
        var response = client.Execute<User>(request);
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            AuthorizationFailed(new SMServiceEventArgs("Credential are incorrect!"));
        }
        else {
            AuthorizationSucceeded(new SMServiceEventArgs(response.Data));
        }
        RequestFinished(new SMServiceEventArgs());
    }
}

2)ViewModel - 用于存储接收数据和绑定的类

public class ViewModel : INotifyPropertyChanged
{
    private SMServiceClient _client;
    public SMServiceClient client { get { return _client; } }

    private Credentials _currentLogging;
    public Credentials currentLogging
    {
        get { return _currentLogging; }
        set
        {
            if (_currentLogging != value)
            {
                _currentLogging = value;
                OnPropertyChanged(new PropertyChangedEventArgs("currentLogging"));
            }
        }
    }

    public ViewModel() 
    {
        _client = new SMServiceClient();
        currentLogging = new Credentials();
    }

    public void AuthUser()
    {
        _client.AuthUser(currentLogging.login, currentLogging.password);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }
}

3)MainWindow.xaml.cs - 应用程序的主窗口

public partial class MainWindow : MetroWindow
{
    public ViewModel _viewModel;
    public MainWindow()
    {
        InitializeComponent();
        _viewModel = new ViewModel();
        _viewModel.client.AuthorizationSucceeded += ServiceClient_AuthorizationSucceeded;
        _viewModel.client.AuthorizationFailed += ServiceClient_AuthorizationFailed;
        _viewModel.client.RequestStarted += ServiceClient_RequestStarted;
        _viewModel.client.RequestFinished += ServiceClient_RequestFinished;

        this.DataContext = _viewModel;
    }

    void ServiceClient_RequestStarted(SMServiceEventArgs args)
    {
        this.Dispatcher.BeginInvoke(new Action(() => { overlayThrobber.Visibility = System.Windows.Visibility.Visible; }), DispatcherPriority.Normal);
    }

    void ServiceClient_RequestFinished(SMServiceEventArgs args)
    {
        this.Dispatcher.BeginInvoke(new Action(() => { overlayThrobber.Visibility = System.Windows.Visibility.Collapsed; }), DispatcherPriority.Normal);
    }

    void ServiceClient_AuthorizationSucceeded(SMServiceEventArgs args)
    {
        _viewModel.loggedUser = args.loggedUser;

        Storyboard storyboard = new Storyboard();
        TimeSpan duration = new TimeSpan(0, 0, 0, 0, 600);
        DoubleAnimation animation = new DoubleAnimation();
        animation.From = 1.0;
        animation.To = 0.0;
        animation.Duration = new Duration(duration);

        Storyboard.SetTargetName(animation, "overlayControl");
        Storyboard.SetTargetProperty(animation, new PropertyPath(Control.OpacityProperty));
        storyboard.Children.Add(animation);
        storyboard.Completed += storyboard_Completed;
        storyboard.Begin(this);
    }

    void ServiceClient_AuthorizationFailed(SMServiceEventArgs args)
    {
        loginErrorBlock.Text = args.message;
    }

    private void LoginForm_LoginButtonClicked(object sender, RoutedEventArgs e)
    {
        _viewModel.AuthUser();
    }

    void storyboard_Completed(object sender, EventArgs e)
    {
        overlayControl.Visibility = System.Windows.Visibility.Collapsed;
    }
}

和Xaml:

<controls:MetroWindow x:Class="ScheduleManager.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sm="clr-namespace:ScheduleManager"
        xmlns:controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
        xmlns:extWpf="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
        Title="Schedule Manager" Height="500" Width="600" MinHeight="500" MinWidth="600">
    <Grid x:Name="mainGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid x:Name="overlayThrobber" Grid.Column="1" Grid.Row="1" Background="Gray" Opacity="0.7" Panel.ZIndex="2000" Visibility="Collapsed">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <controls:ProgressRing x:Name="processThrobber" Grid.Column="1" Grid.Row="1" Foreground="White" IsActive="True" Opacity="1.0"/>
        </Grid>
    </Grid>
</controls:MetroWindow>

整个过程从LoginForm_LoginButtonClicked的调用开始。

我想在SMServiceClient发送数据请求时显示 overlayThrobber 。我已经尝试了很多方法来异步显示它,例如通过Dispatcher.Invoke和Dispatcher.BeginInvoke或创建新的线程,但没有任何作用。我需要在RequestStarted和RequestFinished事件的处理程序中显示/隐藏 overlayThrobber 。也许它不起作用,因为我试图调用在SMServiceClient的处理程序中显示overlayThrobber的功能?你可以给我什么建议吗?

2 个答案:

答案 0 :(得分:1)

罗马,

我通常建议在视图模型上使用“overlayThrobber”元素的可见性连接到的属性。然后你可以改变这个值,UI会自动更新 - 这是使用一个名为MVVM的标准XAML范例(模型 - 视图 - ViewModel)。

“视图”是XAML。它使用数据绑定绑定到ViewModel(在本例中为您的代码)。模型通常是后端,在这种情况下,您可以将通过线路检索的数据视为模型。

所以在这种情况下你会在你的视图模型上公开一个属性,让我们称之为ThrobberVisible ......

私人布尔_throbberVisible;

public bool ThrobberVisible
{
  get { return _throbberVisible; }
  set
  {
    if (value != _throbberVisible)
    {
      _throbberVisible = value;
      this.OnPropertyChanged("ThrobberVisible");
    }
  }
}

这依赖于您还在View Model类上创建OnPropertyChanged方法......

protected void OnPropertyChanged(string propertyName)
{
  var handler = this.PropertyChanged;
  if (null != handler)
    handler(this, new PropertyChangedEventArgs(propertyName));
}

此代码引发属性更改通知,这是UI将侦听的内容。有许多UI框架可以实现这个东西儿童游戏。我使用了来自一个好伙伴和XAML大师Josh的一堆片段。

现在您需要更改XAML,以便将throbber的可见性与ThrobberVisible值相关联。通常你会做以下事情......

... Visibility={Binding ThrobberVisible, Converter={StaticResource boolToVisible}}

将视图模型上属性的可见性挂钩。然后,您需要一个转换器将布尔值true / false值转换为XAML Visible / Collapsed值,例如this类。您将静态资源定义为此布尔转换器,我通常在我的App.Xaml文件中执行此操作,因为我在整个地方使用此转换器。

完成所有这些后,您现在应该只需更改视图模型上的布尔值即可翻转UI元素的可见性。

希望这有帮助!如果代码没有编译,我会道歉,我只是徒手打字。 : - )

答案 1 :(得分:0)

你做的事情是正确的,但你使用Threads Dispatcher而不是UI Dispatcher来更新UI。您可以执行以下操作从另一个线程更新UI。这不仅与Visibility有关,如果您想从另一个线程执行任何类型的UI操作,您必须执行相同操作。在你的MainWindow.Xmal.cs中声明一个像下面这样的本地调度程序并使用它

public partial class MainWindow : MetroWindow
{
 public ViewModel _viewModel;
 private  Dispatcher dispathcer = Dispatcher.CurrentDispatcher;
 public MainWindow()
 {
    InitializeComponent();
    _viewModel = new ViewModel();
    _viewModel.client.AuthorizationSucceeded += ServiceClient_AuthorizationSucceeded;
    _viewModel.client.AuthorizationFailed += ServiceClient_AuthorizationFailed;
    _viewModel.client.RequestStarted += ServiceClient_RequestStarted;
    _viewModel.client.RequestFinished += ServiceClient_RequestFinished;

    this.DataContext = _viewModel;
}

void ServiceClient_RequestStarted(SMServiceEventArgs args)
{
   dispathcer.Invoke(new Action(() => { overlayThrobber.Visibility = System.Windows.Visibility.Visible; }), DispatcherPriority.Normal);
}

void ServiceClient_RequestFinished(SMServiceEventArgs args)
{
    dispathcer.Invoke(new Action(() => { overlayThrobber.Visibility = System.Windows.Visibility.Collapsed; }), DispatcherPriority.Normal);
}