gpt4 book ai didi

c# - 使用 Prism 创建基本加载 View

转载 作者:行者123 更新时间:2023-12-03 10:16:17 25 4
gpt4 key购买 nike

我的 prism 应用程序有很多从我的 View 模型中调用的异步操作。
在某些情况下,我希望禁用 View 并显示某种忙碌指示符,直到 View 模型从异步操作中取回结果。

我虽然创建了一个将实现此行为的基本 View (即具有 IsLoading 的依赖属性,它将禁用 View 并在其上方显示一个忙碌指示器)。
问题是,我不确定如何实现这个基本 View 。
任何帮助将不胜感激,谢谢。

编辑:我认为我写了一个 LoadingView 来完成这项工作。

public class LoadingView : UserControl
{
private object content;


 public bool IsLoading
{
get
{
return (bool)GetValue(IsLoadingProperty);
}
set
{
SetValue(IsLoadingProperty, value);
}
}

private ProgressRing m_RingControl;

public LoadingView()
{
m_RingControl = new ProgressRing();
m_RingControl.IsActive = false;
}

// Using a DependencyProperty as the backing store for IsLoading. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsLoadingProperty =
DependencyProperty.Register("IsLoading", typeof(bool), typeof(LoadingView), new PropertyMetadata(false, IsActivePropertyChanged));

private static void IsActivePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
LoadingView view = d as LoadingView;
if (view != null)
{
// Loading - show ring control
if (((bool)e.NewValue) == true)
{
view.content = view.Content;
view.Content = view.m_RingControl;
view.m_RingControl.IsActive = true;
}
else
{
view.m_RingControl.IsActive = false;
view.Content = view.content;
}
}
}
}

我在 View 模型中使用一些 IsLoading(或 IsBusy)绑定(bind) LoadingView.IsLoading

最佳答案

这是一个可以很快变得非常复杂的主题。

我建议在方法上做一个小的改变——不要将 IsBusy 属性放在基本 View 模型中,而是将其抽象化,以便每个派生的 View 模型都必须实现自己的特定检查。

public class BaseViewModel : INotifyPropertyChanged
{

public abstract bool IsBusy { get; }

}

public class FancyViewModel : BaseViewModel
{

public override bool IsBusy
{
get { return [check #1] && [check #2]...; }
}
}

现在由每个特定的 View 模型来确定它是否忙。一个粗略的机制是有一个计数器,每次启动异步函数时递增,并在操作结束时递减 - 如果它的值等于 0,则没有当前的异步操作。使用标志或计数器时,请注意由于 compiler optimisations 而可能发生的各种属性读取问题。 ,学会在正确的地方使用 volatile 关键字。

或者,您可以使用线程安全 CountdownEvent class 而不是保留计数器.如果你想变得更高级,那么你可以查看 System.Threading namespace 中的各种线程信号机制。 ,或查看 task parallelismTask object .

关于c# - 使用 Prism 创建基本加载 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19219185/

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