【问题标题】:How to update the busyIndicator status in a viewmodel method?如何更新 viewmodel 方法中的 busyIndi​​cator 状态?
【发布时间】:2012-08-20 10:56:34
【问题描述】:

我有一个 web 服务调用,我想在 web 服务收到错误时更新 UI busyIndi​​cator 状态! 这是viewmodel webservice调用完成方法中的代码:

if (e.Error != null)
                {
                    MessageBox.Show(msg);
                    busyIndicator.IsBusy = false;
                    return;
                }

我知道当 UI 对象有多个线程时如何在另一个线程中更新它,但视图模型没有对 busyIndi​​cator 的引用!

【问题讨论】:

    标签: c# silverlight mvvm


    【解决方案1】:

    对于 MVVM 模式做这样的事情

    XAML 文件

      <controlsToolkit:BusyIndicator BusyContent="Fetching Data Please Wait.." IsBusy="{Binding IsBusy}" >
                <Grid >....</Grid>
            </controlsToolkit:BusyIndicator>
    

    查看模型类

    private bool isBusy = false; 
    
    public bool IsBusy 
    
    { 
    
        get { return isBusy; } 
    
        internal set { isBusy = value; OnPropertyChanged("IsBusy"); } 
    

    不,您只需要为将为您工作的属性设置值

    类似于视图模型中的东西

        IsBusy = true; //or false
    

    你有没有尝试过这样的事情,即使用 Dispatcher 来更新 UI

    private void btnClick_Click(object sender, RoutedEventArgs e)
    {
    busyIndicator.IsBusy = true;
    //busyIndicator.BusyContent = "Fetching Data...";
    
    ThreadPool.QueueUserWorkItem((state) =>
    {
    Thread.Sleep(3 * 1000);
    Dispatcher.BeginInvoke(() => busyIndicator.IsBusy = false);
    });
    }
    

    【讨论】:

    • 我不认为更新是问题,他只是不能调用busyIndi​​cator,他的视图模型中没有引用。另外,由于他使用的是视图模型,我假设这是 MVVM 并且无法以这种方式处理点击事件。
    • 我是这样想的,就是想知道如何在不绑定的情况下更新。
    • @mantov - 在这种情况下,您需要将 xaml 的 busyindicator 作为参数传递给 viewmodel 类中的方法,而不是您可以更改该繁忙指示器的值
    • 第二种方式是编译错误!因为 viewmodel 类在 UI 页面的 busyIndi​​cator 上没有引用!
    • @mantov - 正如我提到的,您需要将您的 ui busyindicator 传递给 viewmodel,这是我认为您想要的东西的唯一方法..
    【解决方案2】:

    将忙碌指示符内容绑定到一个字符串。 并将值设置为您要显示的值。

    if (e.Error != null)
                {
                    MessageBox.Show(msg);
                    busyIndicator.IsBusy = false;
                    IndicatorMessage = "There has been an error"
                    return;
                }
    

    然后在您的 XAML 中执行标准绑定。

    【讨论】:

      猜你喜欢
      • 2011-04-02
      • 2011-10-06
      • 2013-04-19
      • 1970-01-01
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多