【发布时间】:2009-11-02 23:38:52
【问题描述】:
我一生都无法弄清楚为什么这不起作用。我有一段简化的 Xaml,如下所示:
<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;
}
}
}
我的 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;
如果我这样做,绑定就会起作用。但这对我来说似乎不正确。我在声明性绑定中遗漏了什么吗?
【问题讨论】:
标签: silverlight data-binding xaml mvvm