是否可以将此代码放入 XAML WPF 中?

编程


大家好。
我从以下位置复制/粘贴此示例代码 DataGrid.ItemsSource 属性 (System.Windows.Controls) | 微软学习[^]

XML
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        x:Name="TestWindow"
        Loaded="WindowLoaded">
    <Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
        <DataGrid x:Name="DataGrid" ItemsSource="{Binding Collection}" />
    </Grid>
</Window>

如您所知,要将 ItemsSource 设置为自动生成列,它在 C# 代码中使用以下代码。

C#
dataGrid1.ItemsSource = Customer.GetSampleCustomerList();

所以我的问题是,是否可以在 XAML 中执行此操作? 我的意思是如何在 XAML WPF 中绑定,而不是在 C# 中?

我尝试过的:

我尝试了下面的代码,但没有运气。 🙁

XML
ItemsSource="{Binding Customer.GetSampleCustomerList}"

解决方案1

我的 WPF 有点生疏,但我建议你设置窗口的 DataContext 到视图模型实例并设置 DataGrid 项目来源为 CustomerList 视图模型中定义的属性。 所以 Xaml 看起来像这样:

C#
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:TestViewModel />
    </Window.DataContext>

    <Grid>
        <DataGrid x:Name="DataGrid" ItemsSource="{Binding CustomerList}" AutoGenerateColumns="True" />
    </Grid>
</Window>

视图模型可以简单地定义为:

C#
public class TestViewModel
 {
     public List<Customer> CustomerList { get; set; }
     public TestViewModel()
     {
         CustomerList = Customer.GetSampleCustomerList();
     }
 }

我会包括 Customer 类如示例中所示,但更新 GetSampleCustomerList 方法,以便它使用 C#12 语法。

C#
public static List<Customer> GetSampleCustomerList()
 {
         return [
         new("A.", "Zero",
             "12 North Third Street, Apartment 45",
             false, true),
         new("B.", "One",
             "34 West Fifth Street, Apartment 67",
             false, false),
         new("C.", "Two",
             "56 East Seventh Street, Apartment 89",
             true, null),
         new("D.", "Three",
             "78 South Ninth Street, Apartment 10",
             true, true)
     ];
 }

コメント

タイトルとURLをコピーしました