如何将WindowInteropHelper重新计算为VM方法?

时间:2015-12-10 00:09:42

标签: c# wpf mvvm oauth

我正在使用WPF中的登录提供程序从auth0跟踪示例WPF应用程序,并尝试使用我的MVVM项目中的代码。但我不确定如何将button click代码重构为可在ViewModel中使用的方法。

我已将代码剪切为void方法,而我得到的错误在new WindowInteropHelper(this).Handle上,如下所示:

"Error  1   The best overloaded method match for 'System.Windows.Interop.WindowInteropHelper.WindowInteropHelper(System.Windows.Window)' has some invalid arguments"

"Error  2   Argument 1: cannot convert from 'MongoDBApp.ViewModels.LoginViewModel' to 'System.Windows.Window'"

我从错误中了解到代码是特定于Window的。有谁知道如何将该代码重新分解为void方法?

这是示例中的按钮点击事件:

    private void LoginWithWidget_Click(object sender, RoutedEventArgs e)
    {
        auth0.LoginAsync(new WindowWrapper(new WindowInteropHelper(this).Handle)).ContinueWith(t =>
        {
            if (t.IsFaulted)
                this.textBox1.Text = t.Exception.InnerException.ToString();
            else
                this.textBox1.Text = t.Result.Profile.ToString();
        },
        TaskScheduler.FromCurrentSynchronizationContext());
    }

这是我对方法的代码的重构,但使用WindowInteropHelper代码时出错:

    private void LoginCustomer(object l)
    {

        auth0.LoginAsync(new WindowWrapper(new WindowInteropHelper(this).Handle)).ContinueWith(t =>
        {
            if (t.IsFaulted)
                MessageBox.Show("Login failed!: ", "Not Logged In", MessageBoxButton.OK, MessageBoxImage.Warning);
            else
                MessageBox.Show("Login succesfull!: ", "Logged In", MessageBoxButton.OK, MessageBoxImage.Warning);
        },
       TaskScheduler.FromCurrentSynchronizationContext());

    }

这是API provider's site

1 个答案:

答案 0 :(得分:0)

执行此操作的常用方法是使用ICommand。

创建一个实现ICommand

的类
public class RelayCommand : ICommand 
{
     public RelayCommand(Action<object> execute)
       : this(execute, null)
   {
   }

    public bool CanExecute(object parameter)
    {
    }

    public void Execute(object parameter)
    {
    }

    public event EventHandler CanExecuteChanged;
} 

我用你需要的所有样板代码赢得了答案,你可以在这里找到: http://www.codeproject.com/Tips/813345/Basic-MVVM-and-ICommand-Usage-Example

您也可以按照该教程,它几乎总结了您想要实现的目标。

然后在您的ViewModel中有ICommand处理程序:

public class MyViewModel 
{
    public ICommand LoginCommand{get; private set;}

    public MyViewModel
    {
        LoginCommand = new RelayCommand(_ => DoSomething );
    }

    public void DoSomething(object obj)
    {
        MessageBox.Show(obj.ToString());
    }
}

最后,在Xaml视图中绑定它:

<Button Width="100" Height="100" Content="{Binding LoginCommand}"/>

这很简单,代码应该如何工作。按照这个例子,它会让你更好地理解。