当我运行应用程序时,我希望看到5个按钮(请参阅下面的XAML中的ItemsControl \ DataTemplate \ Button),每个按钮的内容类似于“55/42”,表示最大广告最低温度。但是,窗口是空白的。我知道这与ItemsControl有关,因为我可以在不使用ItemsControl的情况下显示数据。有人能抓住我的错误吗?
<Window x:Class="Embed_WeatherSummaryAsItemsControl_ToMain.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
FocusManager.FocusedElement="{Binding ElementName=InputCity}"
Title="Weather App" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBox x:Name="InputCity" Grid.Row="0" Width="200" Text="{Binding CityAndOptionalCountry}"></TextBox>
<Button Grid.Row="0" Width="50" Content="Go" Margin="260,0,0,0" Command="{Binding GetWeatherReportCommand}"></Button>
<ItemsControl Grid.Row="1" ItemsSource="{Binding WeatherForecastSummaryCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Path=MaxMinTemperature}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
如下所示,“WeatherForecastSummaryCollection”是ViewModel类的集合属性,“MaxMinTemperature”是集合中item的属性。
public class MainWindowViewModel : ViewModelBase
{
....
private List<WeatherForecastSummary> mWeatherForecastSummaryCollection;
public List<WeatherForecastSummary> WeatherForecastSummaryCollection
{
get { return mWeatherForecastSummaryCollection; }
set
{
mWeatherForecastSummaryCollection = value;
OnPropertyChanged("WeatherForecastSummaryCollection");
}
}
.....
}
public class WeatherForecastSummary
{
public string MaxMinTemperature { get; set; }
}
感谢您的帮助!
答案 0 :(得分:2)
我认为你在这里错过了DataContext。 即使您使用View的代码隐藏,也需要编写
this.DataContext = this;
或者如果您使用其他类作为viewmodel,您可能希望将datacontext指向该类。只需将上面代码中的“this”替换为viewmodels对象即可。 在这种情况下,它将是,
this.DataContext = new MainWindowViewModel();