2012-01-30 70 views
0

我試圖讓Lazy在我的ViewModel中綁定到一個集合。該集合通過MEF加載得很好,但從未顯示在綁定的UI中。爲什麼MEF惰性加載不能在ViewModel中工作?

這裏的UI:

<Window x:Class="TestWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 

    <StackPanel> 
      <ItemsControl ItemsSource="{Binding MyList}"> 
       <ItemsControl.ItemTemplate> 
        <DataTemplate> 
         <Label Content="{Binding ItemTitle}" /> 
        </DataTemplate> 
       </ItemsControl.ItemTemplate> 
      </ItemsControl> 
    <StackPanel> 
</Window> 

的代碼隱藏類:

public partial class TestWindow : Window 
{ 
    public TestWindow() 
    { 
      InitializeComponent(); 
      this.DataContext = new TestVM(); 
    } 
} 

視圖模型:

public class TestVM : INotifyPropertyChanged, IPartImportsSatisfiedNotification 
{ 
    public TestVM() 
    { 
      //I'm using a static class to initiate the import 
      CompositionInitializer.SatisfyImports(this); 
    } 

    public event PropertyChangedEventHandler PropertyChanged = delegate { }; 

    [ImportMany(typeof(MyItemBase))] 
    public Lazy<MyItemBase>[] MyList { get; set; } 

    public void OnImportsSatisfied() 
    { 
      this.PropertyChanged(this, new PropertyChangedEventArgs("MyList")); 
    } 
} 

的基類的項目,以及一些遺傳測試類:

[InheritedExport] 
public class MyItemBase 
{ 
    public MyItemBase() 
    { 

    } 

    public string ItemTitle{ get; set; } 
} 

public class MyItem1: MyItemBase 
{ 
    public MyItem1() 
    { 
     this.ItemTitle = "Item 1"; 
    } 
} 

public class MyItem2: MyItemBase 
{ 
    public MyItem2() 
    { 
     this.ItemTitle = "Item 2"; 
    } 
} 

這工作如果我只是刪除延遲加載。但是,我需要稍後應用一些導出屬性,這意味着要延遲。

回答

2

的問題是,你希望綁定到MyItembase對象的名單,但你的實際結合是MyItembase對象的懶惰arrray。(只要你不叫.value的你懶惰的項目什麼都不會發生)

我的項目我使用一個私人懶惰集合爲mef和一個正常的ObservableCollection爲wpf。順便說一句我寧願構造方法注入你的MEF進口

public class TestVM : INotifyPropertyChanged, IPartImportsSatisfiedNotification 
{ 
public TestVM() 
{ 
     //I'm using a static class to initiate the import 
     CompositionInitializer.SatisfyImports(this); 

     this.MyList = new ObservableCollection(); 
     foreach(var lazyitem in _mefList) 
     { 
      this.MyList.Add(lazyitem.Value); 
     } 
} 

public event PropertyChangedEventHandler PropertyChanged = delegate { }; 

public ObservbableCollection<MyItemBase> MyList{ get; set; } 

[ImportMany(typeof(MyItemBase))] 
private IEnumarable<Lazy<MyItemBase>> _mefList { get; set; } 

public void OnImportsSatisfied() 
{ 
     //this.PropertyChanged(this, new PropertyChangedEventArgs("MyList")); 
} 

}

+0

不知道叫.value的要求。不將項目的添加放入構造函數中會消除異步加載?把它放在OnImportsSatisfied中怎麼樣?如果我能用Rx Linq語句包裝它,情況會更好。 – Random 2012-01-31 15:15:33

+0

標記爲答案,因爲它正確地識別了問題,並提供瞭解決方案。但是,我可能會使用ExportFactory。 – Random 2012-01-31 18:13:04

相關問題