2009-11-02 58 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

相关问题