我必须在单击按钮时在网格中显示 Observable Collection 的内容。在按钮单击(我知道可以使用命令绑定但为简单起见单击处理程序)集合应该填充并显示模型类的名称属性。
视图模型:
public class Sample
{
public ObservableCollection<SchoolModel> ModelCollection { get; set; }
public void GridMethod()
{
ModelCollection = new ObservableCollection<SchoolModel>();
ModelCollection.Add(new SchoolModel() {Id=1, Name="ABC" });
ModelCollection.Add(new SchoolModel() { Id = 2, Name = "PQR" });
ModelCollection.Add(new SchoolModel() { Id = 3, Name = "DEF" });
}
}
模型:
public class SchoolModel : INotifyPropertyChanged
{
private int id;
private string name;
public int Id
{
get
{
return id;
}
set
{
id = value;
OnPropertyChanged("Id");
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
看法:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Content="Click" Click="Button_Click" Grid.Row="0" Grid.Column="0"/>
<ItemsControl ItemsSource="{Binding ModelCollection}" Grid.Row="0" Grid.Column="1" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="{Binding Path=ModelCollection.Count}" Columns="{Binding Path=ModelCollection.Count}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate >
<TextBlock Width="auto" Height="auto" Text="{Binding Path=Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
任何的想法?为什么集合不显示在网格中