gpt4 book ai didi

wpf - 如何在MVVM WPF中刷新UI

转载 作者:行者123 更新时间:2023-12-04 07:25:33 24 4
gpt4 key购买 nike

我的项目基于MVVM模式。

我已经建立了一个树状 View 来显示我的文件系统。
每个文件夹都有一个用于选择当前文件夹的复选框。
选择过程需要一些时间,因此,在操作运行时,有一个按钮被禁用,并且在操作结束时,我启用了该按钮。

我的问题是,当按钮被“禁用”时,我会立即看到它。但是,当按钮返回到启用模式时,我必须执行一些操作(例如单击鼠标)才能看到该按钮已启用。

启用按钮后,如何确保UI会立即更新?

这些是我的按钮:

<Button Content="&lt;- 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;
}

我能做什么?

最佳答案

您可以调整控件的Binding mode TwoWay并定义triggers with PropertyChanged

{Binding ElementName=.., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}

关于wpf - 如何在MVVM WPF中刷新UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12691499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com