gpt4 book ai didi

.net - 在 mvvm Light viewmodel 中使用 Web Context 的问题

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

像往常一样,我正在尝试使用新技术并立即遇到问题。

我有一个 Silverlight 业务应用程序 + MvvmLight。

在我的 View 模型中,我尝试获取登录用户的角色:

    public HomeViewModel()
{
if (IsInDesignMode)
{
// Code runs in Blend --> create design time data.
}
else
{
// Code runs "for real"
DetermineStartableProcesses();
}
}

private void DetermineStartableProcesses()
{
_startableProcesses = new ObservableCollection<WorkflowProcess>(
WebContext.Current.User.Roles.SelectMany(r =>
WorkflowProcess.GetStartableByRole(r))
.Distinct());
}

在运行时,我得到这个异常:
System.Windows.Markup.XamlParseException occurred
Message=The invocation of the constructor on type 'CompanyHR.ViewModel.ViewModelLocator' that matches the specified binding constraints threw an exception. [Line: 18 Position: 57]
LineNumber=18
LinePosition=57
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at CompanyHR.App.InitializeComponent()
at CompanyHR.App..ctor()
InnerException: System.ArgumentNullException
Message=Value cannot be null.
Parameter name: source
StackTrace:
at System.Linq.Enumerable.SelectMany[TSource,TResult](IEnumerable`1 source, Func`2 selector)
at CompanyHR.ViewModel.HomeViewModel.DetermineStartableProcesses()
at CompanyHR.ViewModel.HomeViewModel..ctor()
at CompanyHR.ViewModel.ViewModelLocator..ctor()
InnerException:

看起来 ViewModelLocator 在创建 webcontext 之前在应用程序启动时实例化 ViewModel,这意味着在我的 viewmodel 构造函数中做很多工作对我来说是个坏主意。

那么,我应该在 View 模型的哪个位置检索将获得数据绑定(bind)的数据?

最佳答案

在 App 构造函数中实例化您的 WebContext。然后在调用之前将其添加到 App_startup 中的资源中

public App()
{
Startup += Application_Startup;
Exit += Application_Exit;
UnhandledException += Application_UnhandledException;

if (IsInDesignModeStatic)
{
Services.ServiceLoader.LoadDesignTimeServices();
DispatcherHelper.Initialize();
}
else
{
try
{

ServiceLoader.LoadRunTimeServices();
DispatcherHelper.Initialize();

WebContext webContext = new WebContext();
ApplicationLifetimeObjects.Add(WebContext.Current);

FormsAuthentication fa = new FormsAuthentication();
fa.DomainContext = new Web.Services.AuthenticationDomainContext();
WebContext.Current.Authentication = fa;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

InitializeComponent();
}



private void Application_Startup(object sender, StartupEventArgs e)
{
this.Resources.Add("WebContext", WebContext.Current);

RootVisual = new MainPage();

}

由于我的自定义 AuthenticationDomainContext 和 Membershipprovider,我发现在后面的代码中做这部分更容易......但是 Dereks 也很好用,我只是在让一切正常工作时使用后面的代码。

关于.net - 在 mvvm Light viewmodel 中使用 Web Context 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6116851/

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