7

我有一個Silverlight頁面,從來自不同(RIA服務)彙總了一些數據域業務視圖模型類中獲取數據。如何使用DomainContext.Load來填充ViewModel的屬性?

理想情況下,我希望頁面能夠將其控件綁定到視圖模型對象的屬性,但由於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> 

我的視圖模型是這樣的:

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數據綁定時不一定會填充列表。 (在我的倉庫的斷點顯示正在執行填充到採集的代碼,但是頁面呈現之後。)

可有人請告訴我這樣做的正確方法?

回答

4

的缺少一塊拼圖的是,我需要進行籌款活動時的屬性變化。

我更新視圖模型如下:

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"); 
      } 
     } 
    } 
} 

勢必給這些屬性的控件的屬性更改事件觸發時更新。

相關問題