我不能为了我的生活找出为什么这不起作用。我有一个简单的一块的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;
如果我这样做,结合作品。但是这对我来说并不合适。我在声明性绑定中丢失了什么?
谢谢!我认为它必须是简单的东西,我一定在文档中忽略了它。 – Raumornie 2009-11-03 00:05:52