2010-06-16 46 views
2

我在用戶控件背後的代碼中創建了ObservableCollection。xaml中的WPF ObservableCollection

private void UserControl_Loaded(object sender, RoutedEventArgs e) 
    { 
     Entities db = new Entities(); 
     ObservableCollection<Image> _imageCollection = 
     new ObservableCollection<Image>(); 

     IEnumerable<library> libraryQuery = 
     from c in db.ElectricalLibraries 

     select c; 

     foreach (ElectricalLibrary c in libraryQuery) 
     { 
      Image finalImage = new Image(); 
      finalImage.Width = 80; 

      BitmapImage logo = new BitmapImage(); 
      logo.BeginInit(); 
      logo.UriSource = new Uri(c.url); 
      logo.EndInit(); 

      finalImage.Source = logo; 

      _imageCollection.Add(finalImage); 

     } 

    } 

我需要是基於保存在數據庫中的URL創建的圖像的ObservableCollection:當窗口負載創建它。但我需要一個ListView或其他的ItemsControl綁定到它在XAML文件是這樣的:

但我無法弄清楚如何將的ObservableCollection傳遞給控制的ItemsSource。我試圖創建一個類,然後在xaml文件中創建一個類的實例,但它不起作用。我應該創建一個靜態資源以某種方式>

任何幫助將不勝感激。

回答

4

首先,ObservableCollection是一個局部變量。你需要做的是把它作爲一個私有的全局變量,並公開它的屬性。您可以使用INotifyPropertyChanged接口在實際集合本身更改時自動更新圖像數據。

在您的XAML中,您需要將DataContext設置爲self,然後您可以將公共屬性直接綁定到ItemsSource。您可能希望使用ItemTemplate以自定義方式顯示項目。

乾杯, 亞當的要求

實施例:

在C#:

public MyWindowClass 
{ 
    public ObservableCollection<image> MyImageCollection 
    { 
    get; 
    set; 
    } 
} 

在XAML:

<UserControl 
... 
DataContext="{Binding RelativeSource={RelativeSource Self}}"> 

... 
<ListBox ItemsSource="{Binding MyImageCollection}" ItemTemplate="*yourtemplateresource*" /> 
... 

</UserControl> 

現在,我提到使用INotifyPropertyChanged的原因是如果你嘗試:

MyImageCollection = new ObservableCollection<image>(); 

列表框中的項目不會自動更新。但是,使用ObservableCollection,您需要實現INotifyPropertyChanged,以便基本添加和刪除列表項,而不是而不是

+1

除了您可能想要添加更多細節並修復一個小問題外,技術上正確 - * ObservableCollection *已經實現了* INotifyCollectionChanged *和* INotifyPropertyChanged *,因此不需要在您提及的公共屬性上重新實現/調用它們。 – slugster 2010-06-16 10:35:49

+0

謝謝你的幫助。你能提供一些小小的代碼嗎? – Enzomatric 2010-06-16 10:39:14

+0

@slugster - 抱歉,我的回覆不清楚。我提到INotifyPropertyChanged的原因純粹是爲了更新列表,如果作者自己的公共屬性重新初始化。我可能不應該添加這種多餘的信息... @Cloverness - 添加示例... – 2010-06-16 10:46:25

1

您必須將UserControlDataContext設置到您的收藏:

DataContext = _imageCollection 

你可以做的是,在UserControl_Loaded()方法。

接下來你需要將ListViewItemsSource綁定在XAML:

<ListView ItemsSource="{Binding}"/> 

{Binding}相當於{Binding .}結合到UserControlDataContext。如果你需要「更多的東西」你DataContext您可以改爲創建這樣一個類:

class ViewModel : INotifyPropertyChanged { 
    public ObservableCollection Images { get { ... } } 
    ... 
} 

使用這個類爲DataContext

DataContext = new ViewModel(); 

而更換綁定綁定到Images財產:

<ListView ItemsSource="{Binding Images}"/> 

然後你就可以在其他屬性添加到ViewModel

class ViewModel : INotifyPropertyChanged { 
    public ObservableCollection Images { get { ... } } 
    public String Message { get { ... } set { ... } } 
    ... 
} 

並將其綁定到一個控制:

<TextBlock Text="{Binding Message}"/> 

還記得什麼時候Message財產ViewModel改爲觸發PropertyChanged事件。這將在代碼更改視圖模型屬性時更新UI。

+0

非常感謝。現在我的代碼中有另一個問題。 – Enzomatric 2010-06-16 12:07:24