我不能爲了我的生活找出爲什麼這不起作用。我有一個簡單的一塊的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