问题:
我想用ItemsControl来展示一个竖着排列的数据,就像stackpanel那样竖着展示
可我用ItemsSource绑定,没有任何展示
我用的是一个UserControl,在后台代码上用DataContext绑定了一个School,类里面有个属性是IList<Student>,我想用ItemsControl绑定的就是IList<Student>,展示是Student里面的NAME属性
大概界面上绑定是这样:
<DockPanel>
<ScrollViewer Name="scrollViewer" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<Border Margin="20">
<StackPanel Name="content">
<StackPanel ...>
<TextBlock Text="学校名称"></TextBlock>
<TextBox ... Text="{Binding Name, Mode=TwoWay}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Width="450" Height="35">
<TextBlock Text="学校状态"></TextBlock>
<ComboBox ... ItemsSource="{Binding PlatformTypes}" SelectionChanged="PlatformType_SelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource platformConverter}}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<StackPanel Orientation="Vertical" Width="450" x:Name="selectModelPanel">
<StackPanel Orientation="Horizontal" Width="450">
<TextBlock Width="80" TextAlignment="Right"
VerticalAlignment="Center" Text="学生名字列表"></TextBlock>
<!-- 关注点, start -->
<ItemsControl x:Name="studentList" ItemsSource="{Binding ModelList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border>
<TextBlock Text="{Binding NAME}"></TextBlock>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- 关注点, end -->
</StackPanel>
</StackPanel>
<Button ... Name="addstudent" Click="AddStudent_Click" Content="增加学生"></Button>
</StackPanel>
</Border>
</ScrollViewer>
</DockPanel>
public class School{
public IList<Student> Students {get;set;}
public string Name {get;set;}
...
}
public class Student{
public string NAME {get;set;}
public Sex sex {get;set;}
public short level {get;set;}
...
}
请问一下我该怎么绑定,ItemsControl应该怎么写
要么用ListBox也成,但ListBox我也绑不上QAQ
绑定菜鸟求助...
回答1:
<ListBox ...x:Name="studentList" ItemsSource="{Binding ModelList}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding NAME}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
试试这个方法呢,只用ListBox但是挺丑的
回答2:
<ItemsControl x:Name="studentList" ItemsSource="{Binding ModelList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border>
<ListBox itemsource={binding nameof(类里面有个属性是IList<另一个类>)}>
<ListBox.ItemTemplate>
<TextBlock Text="{Binding NAME}"></TextBlock>
</ListBox.ItemTemplate>
</ListBox>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
回答3:
Listbox 和 Expander效果蛮好的
回答4:
当ViewModel修改后,需要Notify界面刷新,两种方式:
- 实现IPropertyChanged接口,当集合改变后,NotifyPropertyChanged.
- 修改School入下:
public class School{
public ObservableCollection<Student> Students {get;} = new ObservableCollection<Student>();
public string Name {get;set;}
...
}
如果都有这些,那确认下Notify的线程是否为UI线程。