我的项目基于 MVVM 模式。
我已经建立了一个显示我的文件系统的树视图。每个文件夹都有一个用于选择当前文件夹的复选框。选择过程需要一些时间,因此在操作运行时,有一个按钮被禁用,并且在操作结束时我正在启用该按钮。
我的问题是,当按钮被“禁用”时,我会立即看到它。但是,当按钮返回启用模式时,我必须执行一些操作(如鼠标单击)才能看到按钮启用。
如何确保在启用按钮后立即更新 UI?
这些是我的按钮:
<Button Content="<- Back" Margin="5,0,5,0" Width="80" Height="25"
IsEnabled="{Binding CanMoveToPreviousPage, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding Path=NavigateBackCommand, IsAsync=True}" />
<Button Content="{Binding ButtonNextCaption}" Margin="5,0,5,0" Width="80" Height="25"
IsEnabled="{Binding CanMoveToNextPage, UpdateSourceTrigger=PropertyChanged}"
Command="{Binding Path=NavigateNextCommand, IsAsync=True}" />
在我的ViewModel中,我添加了以下代码:
public bool CanMoveToNextPage
{
get
{
return this.CurrentPage != null && this.CurrentPage.CanMoveNext;
}
set
{
if (CurrentPage != null)
{
this.CurrentPage.CanMoveNext = value;
OnPropertyChanged("CanMoveToNextPage");
}
}
}
public bool CanMoveToPreviousPage
{
get { return 0 < this.CurrentPageIndex && CurrentPage.CanMoveBack; }
set
{
if (CurrentPage != null)
{
this.CurrentPage.CanMoveBack = value;
OnPropertyChanged("CanMoveToPreviousPage");
}
}
}
UI 更新发生在我执行鼠标单击或任何击键之后。
这是禁用和启用按钮的操作代码:
void bg_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
DecrementDoneCounter();
if (ThreadSafeCouner == 0)//means all bg workers are done
{
UIlimitation(true);
}
}
private int ThreadSafeCouner; // check how many bgworkers run
public void IncrementDoneCounter() { Interlocked.Increment(ref ThreadSafeCouner); }
public void DecrementDoneCounter() { Interlocked.Decrement(ref ThreadSafeCouner); }
void bg_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
IncrementDoneCounter();
UIlimitation(false);
((bgArguments)e.Argument).SelectedDirectory.CanSelected = false;
MarkItems(((bgArguments)e.Argument).SelectedDirectory, ((bgArguments)e.Argument).IsSelect);
((bgArguments)e.Argument).FreeWorkerAllocation();
((bgArguments)e.Argument).SelectedDirectory.CanSelected = true;
}
//this is the enabling action which execute the propeties setters at the upper part of this post
private static void UIlimitation(bool limit)
{
MainWindowViewModel.Instance.CanMoveToNextPage = limit;
MainWindowViewModel.Instance.CanMoveToPreviousPage = limit;
}
我能做些什么?