WPF ItemsControl 数据绑定
程序员文章站
2022-06-09 16:04:49
...
项目中使用到 ItemsControl 控件使用,代码稍作修改后记录一下。
设计到 mvvm模式下的 ItemsControl 数据绑定。
xaml 代码 :
<ItemsControl
ItemsSource="{Binding m_person}"
Style="{DynamicResource ItemsControlStyle1}"
VirtualizingPanel.IsVirtualizing ="True"
AlternationCount="2" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Name="Border1"
Height="50"
Width="130"
CornerRadius="15"
Margin="5 0 0 5" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition />
</Grid.RowDefinitions>
<Border Grid.Row="0">
<Label Name="Label1" Content="{Binding m_Name}" HorizontalAlignment="Left" Block.TextAlignment="Center" >
</Label>
</Border>
<Border Grid.Row="1">
<Label Name="Label2" Content="{Binding m_Age}" HorizontalAlignment="Left" Block.TextAlignment="Center" >
</Label>
</Border>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
viewmodel只需要把xaml绑定的数据源添加一下即可;
viewmodel代码:
m_person = new ObservableCollection<person>();
for (int i = 0; i < 200; i++)
{
person mperson = new person();
mperson.m_Name = "name" + i;
mperson.m_Age = "age" + i;
m_person.Add(mperson);
}
window.cs 下需要获取控件数据源
代码
public MainWindow()
{
this.DataContext = new CPercon();
InitializeComponent();
}
上一篇: 兄弟回来后都瘦了