WPF C# 数据绑定到 DataGridTextColumn

21

我在这个数据网格视图中很难显示任何数据。 我遵循了一些其他StackOverflow论坛帖子中的建议,但是并没有成功地让内容出现。

<DataGrid 
    x:Name="DataGridEmployees"
    DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
    ItemsSource="{Binding GridView}"
    AutoGenerateColumns="True"
    Loaded="dataGrid1_Loaded"
    Margin="0,2,0,-2" Grid.ColumnSpan="2">
    <DataGrid.Columns>
        <DataGridTextColumn Header="EmployeeId" Width="175" Binding="{Binding Id}"></DataGridTextColumn>
        <DataGridTextColumn Header="Title" Width="175" Binding="{Binding Title}"></DataGridTextColumn>
        <DataGridTextColumn Header="WorkStatus" Width="175" Binding="{Binding WorkStatus}"></DataGridTextColumn>
        <DataGridTextColumn Header="FullName" Width="175" Binding="{Binding FullName}"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

这是在xaml.cs文件中从一个独立的窗口触发的点击事件(?这可能会引起任何问题吗?)

public partial class MainMenu : Window
{
    WpfSampleEntities2 _context = new WpfSampleEntities2();

    public MainMenu()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        EmployeeDetails ed = new EmployeeDetails();
        ed.DataContext = ed.DomainEmployees;
        Binding bin = new Binding("GridView");
        bin.Source = ed.DomainEmployees;

        foreach (var item in ed.DomainEmployees)
        {
            bin.Path.PathParameters.Add(item);
        }

        ed.Show();
    }

}

以下是EmployeeDetails.cs类/视图模型的代码:

[TypeConverter(typeof(DataGridTextColumn))]
public class MVVMEmployee : Employee
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Title { get; set; }
    public string WorkStatus { get; set; }

    public MVVMEmployee() { }
    public MVVMEmployee(int id, string fullName, string title, string workStatus)
    {
        this.Id = id;
        this.FullName = fullName;
        this.Title = title;
        this.WorkStatus = workStatus;
    }
}

我也尝试过使用 XAML

<DataGrid
    x:Name="DataGridEmployees"
    DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"
    ItemsSource="{Binding GridView}"
    AutoGenerateColumns="True"
    Loaded="dataGrid1_Loaded"
    Margin="0,2,0,-2" Grid.ColumnSpan="2">
    <DataGrid.Columns>
        <DataGridTextColumn Header="EmployeeId" Width="175" Binding="{Binding ElementName=Id}" ></DataGridTextColumn>
        <DataGridTextColumn Header="Title" Width="175" Binding="{Binding ElementName=Title}"></DataGridTextColumn>
        <DataGridTextColumn Header="WorkStatus" Width="175" Binding="{Binding ElementName=WorkStatus}"></DataGridTextColumn>
        <DataGridTextColumn Header="FullName" Width="175" Binding="{Binding ElementName=FullName}"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

我觉得你将ItemsSource设置为窗口上的GridView属性,这个属性存在吗? - Chris
EmployeeDetails ed = new EmployeeDetails(); ed.DataContext = ed.DomainEmployees; .... 这里你正在将ed的数据上下文与ed上的一个项目进行分配?是这样吗? - user1656632
EmployeeDetails ed = new EmployeeDetails(); ed.DataContext = ed.DomainEmployees; DomainEmployees是viewmodel的ObservableCollection,而不是单个项。 - DisplayName13579
我投票关闭这个问题,因为提问者没有发布他们遇到的确切问题的详细信息,这是一个旧问题,没有得到适当的答案,并且提问者自2013年12月以来没有出现过。 - slugster
4个回答

2
我建议在我的窗口或者更好的是在我的模型视图类中使用ICollectionView接口。
以下是一个示例MainWindow.xaml.cs类,演示了如何通过代码后台向这个接口类添加数据:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;

namespace WpfAppTest
{
    public partial class MainWindow : Window
    {
        public ICollectionView MyMVVMEmployeeList { get; private set; }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<MVVMEmployee> list = new List<MVVMEmployee>();
            list.Add(new MVVMEmployee(23, "foomaster", "dr", "busy"));
            list.Add(new MVVMEmployee(42, "author", "mister", "dead"));

            MyMVVMEmployeeList = CollectionViewSource.GetDefaultView(list);

            //we call update gui //not needed when using modelview in pure mvvm 
            DataContext = this; 
        }
    }
}

MainWindow.xaml中的绑定应该如下所示:

<Window x:Class="WpfAppTest.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:WpfAppTest"
        mc:Ignorable="d"
        DataContext="MainWindow"
        Title="MainWindow" Height="450" Width="800">
    <!-- for mvvm pattern using the model for datacontext deps e.g. like -->
    <!--  DataContext="{Binding Main,Source={StaticResource Locator}}"> -->
    <Grid>
        <StackPanel Orientation="Vertical">
            <DataGrid x:Name="DataGridEmployees"
                    ItemsSource="{Binding MyMVVMEmployeeList }"
                    AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="EmployeeId" Width="175" Binding="{Binding Id}" ></DataGridTextColumn>
                    <DataGridTextColumn Header="Title" Width="175" Binding="{Binding Title}"></DataGridTextColumn>
                    <DataGridTextColumn Header="WorkStatus" Width="175" Binding="{Binding WorkStatus}"></DataGridTextColumn>
                    <DataGridTextColumn Header="FullName" Width="175" Binding="{Binding FullName}"></DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
            <Button Content="add" HorizontalAlignment="Left" Click="Button_Click"/>
        </StackPanel>
    </Grid>
</Window>

为了使其在此处完全可运行,以下是您的数据类 MVVMEmployee.cs ,不引用基类:

namespace WpfAppTest
{
    public class MVVMEmployee 
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Title { get; set; }
        public string WorkStatus { get; set; }

        public MVVMEmployee() { }
        public MVVMEmployee(int id, string fullName, string title, string workStatus)
        {
            this.Id = id;
            this.FullName = fullName;
            this.Title = title;
            this.WorkStatus = workStatus;
        }
    }
}

请在包含上述示例的情况下更改命名空间WpfAppTest。 我建议不使用代码后台,并在您的模型视图类中以相同方式使用MyMVVMEmployeeList,以更好地遵循mvvm模式。


0

尝试在您的视图模型中添加属性,并使用相同的属性绑定在您的Xaml“GridView”中,然后,此属性类型应为Iobservablecollection,它会触发RaisePropertyChanged()方法。 例如:

        private ObservableCollection<Employee> _GridView = new 
        ObservableCollection<Employee>();
        public ObservableCollection<Employee> Publishers
        {
            get { return _GridView; }
            set { _GridView = value; RaisePropertyChanged(); }
        }

请注意,您必须在 ViewModel 中实现 INotifyPropertyChanged 接口,并将 View 的 DataContext 设置为您的 ViewModel,如下所示:
ViewModel WM = new ViewModel ();
     this.DataContext = WM ;

0
myWindow w = new myWindow();
         w.DataContext = myViewModel;
         w.Show();

DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}"

或者

<Window x:Name="MyWindow" />
    //DataGrid
    {Binding DataContext, ElementName=MyWindow}
    ItemsSource="{Binding MyViewModel.MyList}"

0
你尝试实现的方式并不是正确的方法。首先,你需要分离关注点,避免混淆视图和ViewModel。在ViewModel中创建一个ObservableCollection对象(在你的情况下是MVVMEmployee),它应该作为一个单独的Model实现,并且要实现NotifyPropertyChanged事件并将其附加到你的属性上。然后,在Window.cs构造函数中简单地创建一个ViewModel实例(我们称之为vm),并设置this.DataContext = vm; 然后将DataGrid的ItemsSource绑定到你的viewModel中的集合,如ItemsSource = {Binding MyEmployeesCollection}(不需要RelativeSource)。然后像这样绑定每个文本列,例如 Binding = {Binding FullName}。别忘了在你的Model和ViewModel上都要实现INotifyPropertyChanged。这是一种以清晰的MVVM方式实现你的任务的方法之一。还有其他清晰的方法,例如你可以直接在Window.xaml中将DataContext绑定到你的ViewModel实例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接