【发布时间】:2014-12-30 04:42:05
【问题描述】:
当我运行应用程序时,我希望看到 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; }
}
感谢您的帮助!
【问题讨论】:
-
如何填充集合并将控件绑定到它?
-
你能展示你实际实例化集合并添加5个项目的代码吗?
-
我猜你首先将一个空列表分配给
WeatherForecastSummaryCollection,然后添加5个项目(这是标准方式)。但列表不会发送有关内容更改的通知。将类型List<WeatherForecastSummary>更改为ObservableCollection<WeatherForecastSummary>会有所帮助。 -
是的,就是这样 - 我忘了让列表可见。谢谢gomi42!!
标签: wpf xaml mvvm itemscontrol