DataGridComboBoxColumn使用示例
时间: 2024-02-04 19:04:18 浏览: 88
DataGridComboBoxColumn 通过XAML绑定示例 含Enum的绑定
4星 · 用户满意度95%
DataGridComboBoxColumn是WPF中的一种控件,用于在DataGrid中创建下拉选项。示例代码如下:
1.创建一个名为ComboColumn的DataGridComboBoxColumn并添加到DataGrid中:
```
<DataGridComboBoxColumn x:Name="ComboColumn" Header="状态" SelectedItemBinding="{Binding Status, Mode=TwoWay}">
<DataGridComboBoxColumn.ElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding AvailableStatuses}" />
<Setter Property="IsReadOnly" Value="True" />
</Style>
</DataGridComboBoxColumn.ElementStyle>
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding AvailableStatuses}" />
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
```
2.在ViewModel中定义可用的状态列表和当前项目的状态:
```
public class MyViewModel
{
public List<string> AvailableStatuses { get; set; }
public string Status { get; set; }
public MyViewModel()
{
AvailableStatuses = new List<string> { "未开始", "进行中", "已完成" };
Status = "未开始";
}
}
```
3.在MainWindow中为DataGrid指定数据源:
```
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var viewModel = new MyViewModel();
DataContext = viewModel;
var items = new List<MyItem>
{
new MyItem { Name = "项目1", Status = "未开始" },
new MyItem { Name = "项目2", Status = "进行中" },
new MyItem { Name = "项目3", Status = "已完成" }
};
MyDataGrid.ItemsSource = items;
}
}
public class MyItem
{
public string Name { get; set; }
public string Status { get; set; }
}
```
4.运行应用程序并查看DataGridComboBoxColumn中的下拉列表。
希望这个示例对你有所帮助!
阅读全文