2009-11-02 40 views
0

我不能爲了我的生活找出爲什麼這不起作用。我有一個簡單的一塊的XAML看起來像這樣:可以聲明性地將ItemsContol.ItemsSource綁定到Silverlight中的ObservableCollection嗎?

<UserControl x:Class="Foo.MainPage" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"> 
    <Grid x:Name="LayoutRoot"> 
     <ScrollViewer VerticalAlignment="Stretch" 
         Background="Black" 
         HorizontalScrollBarVisibility="Auto" 
         VerticalScrollBarVisibility="Auto" > 
      <ItemsControl x:Name="PictureItemsControl" 
          ItemsSource="{Binding Pics}"> 
       <ItemsControl.ItemsPanel> 
        <ItemsPanelTemplate> 
         <StackPanel Orientation="Horizontal" 
            VerticalAlignment="Center" 
            HorizontalAlignment="Center" /> 
        </ItemsPanelTemplate> 
       </ItemsControl.ItemsPanel> 
       <ItemsControl.ItemTemplate> 
        <DataTemplate> 
         <StackPanel> 
          <Image Source="{Binding Location}" 
            Height="200" 
            Width="200" 
            Stretch="UniformToFill" /> 
          <TextBlock FontFamily="Verdana" 
             FontSize="16" 
             Foreground="White" 
             Text="{Binding Name}" /> 
         </StackPanel> 
        </DataTemplate> 
       </ItemsControl.ItemTemplate> 
      </ItemsControl> 
     </ScrollViewer> 
    </Grid> 
</UserControl> 

在代碼隱藏我的MainPage.xaml中,我有這樣的:

namespace Foo 
{ 
    public partial class MainPage : UserControl 
    { 
     public FooViewModel viewModel; 

     public MainPage() 
     { 
      InitializeComponent(); 
      viewModel = new FooViewModel(); 
      this.DataContext = viewModel; 
     } 

    } 
} 

我的視圖模型看起來像這樣:

namespace Foo 
{ 
    public class FooViewModel:INotifyPropertyChanged 
    { 
     public ObservableCollection<Pic> Pics; 
     public FooViewModel() 
     { 
      Pics = new ObservableCollection<Pic>(); 
      Pic.GetPics(Pics); 
     } 

     //More code here... 
    } 
} 

而Pic只是一個簡單的類,它有一些公共屬性和一個靜態方法,用可測試數據填充可觀察集合。問題是,我沒有看到任何綁定在我的ItemsControl發生的事情,除非我這行添加到我的構造函數的MainPage:

PictureItemsControl.ItemsSource = viewModel.Pics; 

如果我這樣做,結合作品。但是這對我來說並不合適。我在聲明性綁定中丟失了什麼?

回答

3

您需要將「Pics」更改爲屬性,而不是字段。你不能直接將數據綁定到一個字段。更改圖片爲:

public ObservableCollection<Pic> Pics { get; private set; } 

該工作案例的工作原理是因爲您綁定到ViewModel和Pics間接。

+0

謝謝!我認爲它必須是簡單的東西,我一定在文檔中忽略了它。 – Raumornie 2009-11-03 00:05:52

0

是的,你需要在ItemControl(ListBox,TabControl,ComboBox)上指定ItemsSource來將數據綁定到它。

+0

我不明白你的迴應。我可以在代碼中綁定到ItemsSource,但Xaml的平衡線似乎不起作用。你能更具體地說明我不包括在xaml中嗎? – Raumornie 2009-11-02 23:46:10

相關問題