Binding Collection

DataContext:  

1. 通常可以用页面绑定一个ViewModel的实例,通过设置页面的DataContext 属性。

var viewModel = new MainWindowViewModel(path);

window.DataContext = viewModel;

2. 也可以用一个Control绑定一个Object的实例,可以在code中设置或 通过Windows.Resource 来 添加: 

<Window.Resources><ObjectDataProvider x:Key="MyPhotos" ObjectType="{x:Type local:PhotoList}"/></Window.Resources>

<ListBox ItemsSource="{Binding Source={StaticResource MyPhotos}}"

3. 注意ItemsSource 绑定的是实现 IEnumerable的集合, 而DataContext 是绑定一个实例,一个object,可以是任何类型的。

 

ItemsControl:

<ItemsControl ItemsSource="{Binding Path=Commands}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=DisplayName}"></Label>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

转载于:https://www.cnblogs.com/leonwcy/archive/2013/03/01/2939442.html

WPF DataGrid 是一种强大的控件,可以用于在 WPF 应用程序中显示表格数据。DataGrid 可以使用 Binding 数据来绑定到数据源,这使得在 DataGrid 中显示数据变得非常简单。 下面是一个简单的示例,展示如何在 DataGrid 中使用 Binding 数据: 1. 首先,创建一个数据类,用于表示要在 DataGrid 中显示的数据。例如,在此示例中,我们创建一个名为 Person 的类: ```csharp public class Person { public string Name { get; set; } public int Age { get; set; } public string Email { get; set; } } ``` 2. 接下来,在 XAML 中创建一个 DataGrid 控件,并将其绑定到数据源。例如,在此示例中,我们将 DataGrid 绑定到一个名为 people 的 ObservableCollection<Person> 对象: ```xaml <DataGrid ItemsSource="{Binding people}" AutoGenerateColumns="True"/> ``` 3. 最后,在代码中设置 DataContext,并将 people 集合添加到 DataContext 中: ```csharp public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // Create a collection of people ObservableCollection<Person> people = new ObservableCollection<Person>(); people.Add(new Person { Name = "John", Age = 30, Email = "john@example.com" }); people.Add(new Person { Name = "Jane", Age = 25, Email = "jane@example.com" }); people.Add(new Person { Name = "Bob", Age = 40, Email = "bob@example.com" }); // Set the DataContext DataContext = new { people }; } } ``` 现在,当运行应用程序时,将显示一个包含三个人的表格,其中每个人都有一个名称、年龄和电子邮件地址。这些数据将使用 Binding 数据绑定到 DataGrid 中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值