调用一组 属性 更改的更好方法

A better way to invoke a group of property changes

我有一个 wpf c# 应用程序。

我会有这样的功能:

private void ReSetScreen()
{
    if (!Dispatcher.CheckAccess())
    {
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
        {
            ucCustomerNew.Visibility = Visibility.Hidden;
            ucCustomerResults.Visibility = Visibility.Hidden;             
        }));
    }
    else
    {
        ucCustomerNew.Visibility = Visibility.Hidden;
        ucCustomerResults.Visibility = Visibility.Hidden;           
    }
}

这段代码基本上是说检查是否需要 'invoke'(因为在不同的线程上),如果需要,请使用适当的方式隐藏我创建的 2 个用户控件。

我的应用程序中有很多这样的代码段。

我可以将上面的代码重构为:

private void ReSetScreen()
{
    if (!Dispatcher.CheckAccess())
    {
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
        {
            DoMystuff()            
        }));
    }
    else
    {
        DoMystuff()
    }
}

void DoMystuff()
{
    ucCustomerNew.Visibility = Visibility.Hidden;
    ucCustomerResults.Visibility = Visibility.Hidden;      
}

然后如果我在任何需要的地方都这样做,我将不得不基本上创建 'shadow' 函数。

是否有更好的设计模式可供我使用?

附加: 带扩展名的代码示例(给出错误:

没有给定的参数对应于 'InvokeOnMainThread(Control, Action)'

的所需形式参数 'method'
public partial class MainWindow : Window
{
    private void ReSetScreen()
    {
        WorkingClasses.Shared.InvokeOnMainThread(() =>  { ucCustomerNew.Visibility = Visibility.Hidden; ucCustomerResults.Visibility = Visibility.Hidden; });
    }

public  static class Shared
{
    public static void InvokeOnMainThread(this Control control, Action method)
    {
        //if (method == null) throw new ArgumentNullException("method");
        if (!control.Dispatcher.CheckAccess())
        {
            Application.Current.Dispatcher.BeginInvoke(method);
            return;
        }

        method();
    }
}

此模式有效:

private void ReSetScreen()
{
    if (!Dispatcher.CheckAccess())
    {
        Application.Current.Dispatcher.BeginInvoke(ReSetScreen);
        return;
    }

    ucCustomerNew.Visibility = Visibility.Hidden;
    ucCustomerResults.Visibility = Visibility.Hidden;           
}

如果您的方法需要参数,请将 lambda 传递给 BeginInvoke 而不是方法组。

public static class ControExtensions
  {
    public static void InvokeOnMainThread(this Control control, Action method)
    {
      if (method == null) throw new ArgumentNullException("method");
      if (!control.Dispatcher.CheckAccess()) {
        Application.Current.Dispatcher.BeginInvoke(method);
        return;
      }

      method();
    }
  }

将该扩展放在 WPF 实用程序项目中,这样您就可以重用它。 而且使用起来非常简单:

this.InvokeOnMainThread(this.DoMyStuff);