【问题标题】:How to call a function after the viewModel is downloaded?下载viewModel后如何调用函数?
【发布时间】:2014-04-07 15:21:37
【问题描述】:

我开始搜索,完成后我完成了 viewModel,如果我没有找到任何东西,我想显示一条消息。

到目前为止,我有 3 种方法:

1.) 将 App.ViewModel.LoadData() 转换为 async-await-method,然后启动我的函数。

2.) 做一些类似的事情,但是有一个函数:

void NewSearch_Loaded(object sender, RoutedEventArgs e)
{
    Binding binding = new Binding("IsLoadingJobs") { Source = DataContext };
    BindingOperations.SetBinding(
        prog, ProgressIndicator.IsIndeterminateProperty, binding);
}

3.) 黑客攻击。

1. 方法效果不佳,因为我以前从未使用过 async-await,而且它看起来并不容易。 2. 方法听起来更容易,但我找不到任何“绑定”来启动函数。 hacking 方法很容易,但不是很好:在 viewModel 中,我看到我得到一个空数组,可以填写 1 个特殊的触发词或其他东西,然后在视图端用 if 询问这个词。可以,但我不喜欢那样。

有什么想法吗?

【问题讨论】:

  • 拥抱async/await。如果您有困难,请将其作为一个单独且更具体的问题提出。关于这个主题已经有很多很好的答案,例如this.
  • 好的,我会处理这个。我的问题是/是我不知道要搜索什么。当我找到一种方法时,它并不自动意味着这是实现它的方法。这就是为什么我要求最好/最好的方法;)然后异步/等待。谢谢 :)
  • 一个好决定。 async/wait wiki 有一些很棒的资源可供参考:stackoverflow.com/tags/async-await/info

标签: c# mvvm windows-phone-8 binding async-await


【解决方案1】:

补充@Toni 提到的内容

举个简单的例子,在上述更改之后,您的视图模型将如下所示

public class ViewModel
{
   /// <summary>
    /// Gets or sets a value indicating whether the search resulted in data
    /// </summary>
    public bool? HasResult
    {
        get
        {
            return this.hasResult;
        }
        set
        {
            this.hasResult = value;
            this.RaisePropertyChanged("HasResult");
        }
    }

   /// <summary>
    /// Gets or sets a value indicating a search result message
    /// </summary>
    public bool? SearchResultMessage
    {
        get
        {
            return this.searchResultMessage;
        }
        set
        {
            this.hasResult = value;
            this.RaisePropertyChanged("SearchResultMessage");
        }
    }

  //Your command or action that searches for results
  public void Search()
  {
    //Does what it used to do

    //Check if there is result
    if(results.Count == 0)
    {
       this.HasResult = false;
       this.SearchResultMessage = "Nothing is loaded";
    }
  }
}

使用 boolean to visibility converter 将 HasResult 绑定到视图(这包括其可见性将受此属性状态影响的元素) 像这样的

<TextBlock Visibility = "{Binding HasResult, Converter={StaticResource BoolToVisConv}}" Text="{Binding SearchResultMessage}" ></TextBlock>

您始终可以根据您希望视图的行为方式来改变这种方法,例如也表明进度,但其要点是遵循MVVM pattern

【讨论】:

    【解决方案2】:

    首先,警告:不要写async void LoadDataAsync,而是写async Task LoadDataAsync。另外不要忘记在函数末尾添加Async

    现在,您应该具有指示搜索/加载是否正在进行以及是否已完成的属性。这些通常用于切换某些 UI 元素的可见性,例如进度条或“未加载任何内容”的消息。

    这是一个干净的、基于 MVVM 的模式,用于显示正在进行的操作指示器以及显示操作已完成。而且没有结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      相关资源
      最近更新 更多