gpt4 book ai didi

silverlight - 如何使用 DomainContext.Load 填充 ViewModel 的属性?

转载 作者:行者123 更新时间:2023-12-04 02:56:13 26 4
gpt4 key购买 nike

我有一个 Silverlight 页面,它从 View 模型类中获取数据,该类聚合了来自各种(RIA 服务)域服务的一些数据。

理想情况下,我希望页面能够将其控件数据绑定(bind)到 View 模型对象的属性,但是因为 DomainContext.Load异步执行查询,页面加载时数据不可用。

我的 Silverlight 页面具有以下 XAML:

<navigation:Page x:Class="Demo.UI.Pages.WidgetPage" 
// the usual xmlns stuff here...
xmlns:local="clr-namespace:Demo.UI.Pages" mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"

d:DataContext="{d:DesignInstance Type=local:WidgetPageModel, IsDesignTimeCreatable=False}"

d:DesignWidth="640" d:DesignHeight="480"
Title="Widget Page">
<Canvas x:Name="LayoutRoot">
<ListBox ItemsSource="{Binding RedWidgets}" Width="150" Height="500" />
</Canvas>
</navigation:Page>

我的 ViewModel 看起来像这样:
public class WidgetPageModel
{
private WidgetDomainContext WidgetContext { get; set; }

public WidgetPageModel()
{
this.WidgetContext = new WidgetDomainContext();

WidgetContext.Load(WidgetContext.GetAllWidgetsQuery(), false);

}

public IEnumerable<Widget> RedWidgets
{
get
{
return this.WidgetContext.Widgets.Where(w => w.Colour == "Red");
}
}
}

我认为这种方法从根本上肯定是错误的,因为 Load 的异步性质意味着当 ListBox 数据绑定(bind)时,不一定要填充小部件列表。 (我的存储库中的断点显示正在执行要填充到集合的代码,但仅在页面呈现之后。)

有人可以告诉我正确的方法吗?

最佳答案

难题中缺少的部分是我需要在属性更改时引发事件。

我更新的 ViewModel 如下:

public class WidgetPageModel : INotifyPropertyChanged
{

public event PropertyChangedEventHandler PropertyChanged;

protected void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

private WidgetDomainContext WidgetContext { get; set; }

public WidgetPageModel()
{
this.WidgetContext = new WidgetDomainContext();

WidgetContext.Load(WidgetContext.GetAllWidgetsQuery(),
(result) =>
{
this.RedWidgets = this.WidgetContext.Widgets.Where(w => w.Colour == "Red");
}, null);

}

private IEnumerable<Widget> _redWidgets;
public IEnumerable<Widget> RedWidgets
{
get
{
return _redWidgets;
}
set
{
if(value != _redWidgets)
{
_redWidgets = value;
RaisePropertyChanged("RedWidgets");
}
}
}
}

当属性更改事件触发时,绑定(bind)到这些属性的控件会更新。

关于silverlight - 如何使用 DomainContext.Load 填充 ViewModel 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3066597/

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