我正在尝试使用 WPF,但遇到了一个我似乎无法弄清楚的问题,尽管我之前已经使用 Silverlight 完成了一些工作并成功使用了 DataContexts、Data Bindings 和 INPC。这次我卡住了...
我正在使用此代码创建应用程序主窗口的实例:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
var viewModel = new MainVM(); //implements INotifyPropertyChanged
viewModel.Load("Brighton+UK");
window.DataContext = viewModel;
window.weatherList.ItemsSource = viewModel.WeatherInfo; //THIS WORKS
window.Show();
}
当我像这样运行应用程序时,一切都很好,主窗口上的 ListBox 显示在 MainVM 的 WeatherInfo ObservableCollection 中找到的项目,就像它应该的那样。
但是,当我注释掉该行然后进入我的主窗口的 XAML,并在 XAML 中设置 weatherList ListBox 的 ItemsSource 属性时,如下所示:
<ListBox x:Name="weatherList"
Grid.Row="0"
ItemContainerStyle="{StaticResource stretched}"
ItemsSource="{Binding WeatherInfo}" />
尽管我确实将 MainWindow 的 DataContext 设置为 MainVM 的一个实例(如 C# 代码摘录中所示),但该列表并未像我预期的那样填充。
有人可以向我解释一下,为什么?
==编辑==
我所有主窗口的 XAML:
<Window x:Class="DataTemplates.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Google World Weather"
SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen"
xmlns:local="clr-namespace:DataTemplates" >
<!--Resources section-->
<Window.Resources>
<!--Styles-->
<Style TargetType="Label">
<Setter Property="FontSize" Value="24" />
<Setter Property="Margin" Value="10,0,0,0" />
</Style>
<Style x:Key="stretched" TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</Window.Resources>
<!--Command binding definition-->
<Window.CommandBindings>
<CommandBinding Command="Refresh" x:Name="cmdLoadWeatherForecast" CanExecute="cmdLoadWeatherForecast_CanExecute" Executed="cmdLoadWeatherForecast_Executed" />
</Window.CommandBindings>
<!--UI design - layout of individual controls-->
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ListBox x:Name="weatherList" Grid.Row="0" ItemContainerStyle="{StaticResource stretched}" ItemsSource="{Binding WeatherInfo}" />
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Margin="10" >
<TextBox Text="Brighton UK" Name="txtLocation" Width="200" FontSize="20" Margin="10" FocusManager.FocusedElement="{Binding txtLocation}" />
<Button IsDefault="True" Name="btnLoadForecast" Content="Load Weather Forecast" Command="Refresh" Margin="0,10,10,10" Padding="10"/>
</StackPanel>
</Grid>
</Window>