wpf prism<ItemsControl ItemsSource 详解代码示例
时间: 2024-02-05 16:12:15 浏览: 217
以下是一个使用WPF Prism框架中的ItemsControl控件和绑定数据源的示例代码:
1. 在XAML中添加ItemsControl控件
```xml
<ItemsControl x:Name="MyItemsControl" ItemsSource="{Binding MyItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- 在这里定义控件模板 -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
```
2. 在ViewModel中定义数据源和属性
```csharp
private ObservableCollection<MyItemViewModel> _myItems;
public ObservableCollection<MyItemViewModel> MyItems
{
get { return _myItems; }
set { SetProperty(ref _myItems, value); }
}
```
3. 在ViewModel的构造函数中初始化数据源
```csharp
MyItems = new ObservableCollection<MyItemViewModel>();
MyItems.Add(new MyItemViewModel() { Title = "Item 1", Description = "Description for Item 1" });
MyItems.Add(new MyItemViewModel() { Title = "Item 2", Description = "Description for Item 2" });
MyItems.Add(new MyItemViewModel() { Title = "Item 3", Description = "Description for Item 3" });
```
4. 在MyItemViewModel中定义需要绑定的属性
```csharp
public class MyItemViewModel : BindableBase
{
private string _title;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private string _description;
public string Description
{
get { return _description; }
set { SetProperty(ref _description, value); }
}
}
```
5. 在DataTemplate中定义控件模板,绑定对应的属性
```xml
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}" />
<TextBlock Text="{Binding Description}" />
</StackPanel>
</DataTemplate>
```
这样,就可以在界面中展示绑定的数据源了。
阅读全文