ItemsControl datagrid 案例
时间: 2024-05-13 17:15:44 浏览: 85
以下是一个使用ItemsControl控件实现的DataGrid案例:
XAML代码:
```xml
<Grid>
<ItemsControl ItemsSource="{Binding Customers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding FirstName}" Grid.Column="0" Margin="5"/>
<TextBlock Text="{Binding LastName}" Grid.Column="1" Margin="5"/>
<TextBlock Text="{Binding Age}" Grid.Column="2" Margin="5"/>
<TextBlock Text="{Binding Gender}" Grid.Column="3" Margin="5"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
```
C#代码:
```csharp
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 数据绑定
DataContext = new ViewModel();
}
}
public class ViewModel
{
public ObservableCollection<Customer> Customers { get; set; }
public ViewModel()
{
Customers = new ObservableCollection<Customer>
{
new Customer { FirstName = "John", LastName = "Doe", Age = 30, Gender = "Male" },
new Customer { FirstName = "Jane", LastName = "Doe", Age = 25, Gender = "Female" },
new Customer { FirstName = "Bob", LastName = "Smith", Age = 40, Gender = "Male" },
new Customer { FirstName = "Alice", LastName = "Johnson", Age = 35, Gender = "Female" }
};
}
}
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
```
这个案例中,我们使用了ItemsControl控件绑定了一个Customer列表,然后使用DataTemplate定义了每个Customer对象的呈现方式。在这里,我们将每个Customer的FirstName、LastName、Age和Gender属性分别显示在了四个列中。这样,我们就实现了一个简单的DataGrid。
阅读全文