c# - 将 WPF DataGrid 升级到 UWP 支持的 DataGrid
问题描述
我正在将 WPF 应用程序升级到 UWP,并且一直在升级 DataGrid 控件。我正在尝试升级 System.Windows.Controls.DataGrid(旧的 WPF 控件)-> Microsoft.Toolkit.Uwp.UI.Controls.DataGrid(新的 MS 推荐的社区控件)
旧版本运行良好。它从 .NET DataTable 填充网格。XAML:
<DataGrid SelectionMode="Single" SelectionChanged="dataGridSongs_SelectionChanged" BorderThickness="1" BorderBrush="LightGray" Margin="0 0" IsReadOnly="True" GridLinesVisibility="None" Name="dataGridSongs" ItemsSource="{Binding}">
</DataGrid>
后面的代码:
public MainWindow()
{
initializing = true;
InitializeComponent();
DataTable dt = dbHelper.GetAllSongs();
dataGridSongs.DataContext = dt.DefaultView;
dataGridSongs.HeadersVisibility = DataGridHeadersVisibility.None;
initializing = false;
}
新的 UWP DataGrid 给了我一个错误:“BindingExpression 路径错误:在 'System.Data.DataRowView' 上找不到 'Item' 属性”并且网格中填充了一些奇怪的数据:
新的 UWP 应用 XAML:
<controls:DataGrid x:Name="dataGridSongs" ItemsSource="{Binding}">
</controls:DataGrid>
后面的代码:
public MainPage()
{
initializing = true;
this.InitializeComponent();
DataTable dt = dbHelper.GetAllSongs();
dataGridSongs.DataContext = dt.DefaultView;
//dataGridSongs.ItemsSource = dt.DefaultView;
}
我假设我用错误的对象填充网格,但是,我找不到这个简单场景的任何示例。
解决方案
您可以参考以下示例,该示例显示如何将 a 绑定DataGrid
到数据源:
public class Customer
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String Address { get; set; }
public Boolean IsNew { get; set; }
public Customer(String firstName, String lastName,
String address, Boolean isNew)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
this.IsNew = isNew;
}
}
public class ViewModel
{
private List<Customer> m_customers;
public List<Customer> Customers { get { return m_customers; }
}
public ViewModel()
{
m_customers = new List<Customer>(new Customer[4] {
new Customer("A.", "Zero",
"12 North Third Street, Apartment 45",
false),
new Customer("B.", "One",
"34 West Fifth Street, Apartment 67",
false),
new Customer("C.", "Two",
"56 East Seventh Street, Apartment 89",
true),
new Customer("D.", "Three",
"78 South Ninth Street, Apartment 10",
true)
});
}
}
主页类
public sealed partial class MainPage : Page
{
public ViewModel MyViewModel;
public MainPage()
{
this.InitializeComponent();
MyViewModel = new ViewModel();
}
}
主页.xaml
<controls:DataGrid x:Name="dataGrid" AutoGenerateColumns="True"
ItemsSource="{x:Bind MyViewModel.Customers}">
</controls:DataGrid>
您可以参考文档以获取有关数据绑定和自定义列的更多信息DataGrid
。
推荐阅读
- android - JIO 网络中的网络缓存 REST API 请求
- python - 在 python 中解码 base64(例如 :: Q29ycsOqYQ== 成 Corrêa)
- reactjs - 使用 browserRouter 通过 URL 无法访问的参数反应路由
- kubernetes - 如何将 Prometheus 与运行在不同主机上的 Kubernetes 集成?
- javascript - Angular ui-select ng-blur
- c# - 如何随机创建一个迷宫
- oracle - 一起使用行透视
- modularization - 为什么以组件/模块的方式编写代码很重要?
- python - Python中解析多个Json对象并合并成单个json对象
- 32bit-64bit - 可以将 64 位库链接到 32 位应用程序吗?