如何正确地将对象绑定到 WPF DataGrid?

发布于 2024-09-04 19:49:33 字数 2614 浏览 6 评论 0原文

我正在尝试让 WPF DataGrid 从我正在构建的用户控件中工作。事情似乎进展顺利。但我在 IDE 的输出窗口中注意到了这条消息:

System.Windows.Data 错误:39:BindingExpression 路径错误:在“对象”“对象”(HashCode=18165668) 上找不到“名称”属性。绑定表达式:路径=名称; DataItem='对象' (HashCode=18165668);目标元素是“TextBlock”(名称=“”);目标属性是“文本”(类型“字符串”) System.Windows.Data 错误:39:BindingExpression 路径错误:在“对象”“对象”(HashCode=18165668) 上找不到“部门”属性。绑定表达式:路径=名称; DataItem='对象' (HashCode=18165668);目标元素是“TextBlockComboBox”(名称=“”);目标属性是“SelectedItem”(类型“String”)

我想做的是从 XAML 手动将列​​添加到 DataGrid 并将它们绑定到 C# 代码中的对象。

这是我的 XAML 代码:


    <UserControl x:Class="Sting.Utilities.MyDataGrid" Name="This"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
        Height="600" Width="800">
        <Grid>
            <toolkit:DataGrid AutoGenerateColumns="False" Name="myDataGrid" Margin="10" ItemsSource="{Binding ElementName=This, Path=MyData}">
                <toolkit:DataGrid.Columns>
                    <toolkit:DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                    <toolkit:DataGridComboBoxColumn Header="Department" x:Name="_Departmens" SelectedItemBinding="{Binding Department}"/>
                </toolkit:DataGrid.Columns>
            </toolkit:DataGrid>
        </Grid>
    </UserControl>

这是我的 C# 代码:


    namespace Sting.Utilities
    {
        /// 
        /// Interaction logic for UserControl1.xaml
        /// 
        public partial class MyDataGrid : UserControl
        {
            DataTable _myData;
            public DataTable TestData { get { return _testData; } }

            public MyDataGrid()
            {
                // Initialize data table
                _myData = new DataTable();
                _testData.Columns.Add(new DataColumn("Name", typeof(string)));
                _testData.Columns.Add(new DataColumn("Department", typeof(string)));

                // Temp Code: User should add rows
                DataRow row = _testData.NewRow();
                row["Name"] = "John Smith";
                row["Department"] = "Accounting";
                _testData.Rows.Add(row);

                // Initialize combo boxes
                List departmentComboBoxList = new List() {"Accounting", "Purchasing", "Engineering"};
                _Departments.ItemsSource = departmentComboBoxList;
            }
        }
    }


欢迎任何想法。谢谢。

I'm trying to get a WPF DataGrid to work from a user control I'm building. Things seems to work fine. But I noticed this message in the Output window in the IDE:

System.Windows.Data Error: 39 : BindingExpression path error: 'Name' property not found on 'object' ''Object' (HashCode=18165668)'. BindingExpression:Path=Name; DataItem='Object' (HashCode=18165668); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
System.Windows.Data Error: 39 : BindingExpression path error: 'Department' property not found on 'object' ''Object' (HashCode=18165668)'. BindingExpression:Path=Name; DataItem='Object' (HashCode=18165668); target element is 'TextBlockComboBox' (Name=''); target property is 'SelectedItem' (type 'String')

What I'm trying to do is to manually add columns to DataGrid from XAML and bind them to an object that I have in the C# code.

Here is my XAML code:


    <UserControl x:Class="Sting.Utilities.MyDataGrid" Name="This"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
        Height="600" Width="800">
        <Grid>
            <toolkit:DataGrid AutoGenerateColumns="False" Name="myDataGrid" Margin="10" ItemsSource="{Binding ElementName=This, Path=MyData}">
                <toolkit:DataGrid.Columns>
                    <toolkit:DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                    <toolkit:DataGridComboBoxColumn Header="Department" x:Name="_Departmens" SelectedItemBinding="{Binding Department}"/>
                </toolkit:DataGrid.Columns>
            </toolkit:DataGrid>
        </Grid>
    </UserControl>

And here is my C# code:


    namespace Sting.Utilities
    {
        /// 
        /// Interaction logic for UserControl1.xaml
        /// 
        public partial class MyDataGrid : UserControl
        {
            DataTable _myData;
            public DataTable TestData { get { return _testData; } }

            public MyDataGrid()
            {
                // Initialize data table
                _myData = new DataTable();
                _testData.Columns.Add(new DataColumn("Name", typeof(string)));
                _testData.Columns.Add(new DataColumn("Department", typeof(string)));

                // Temp Code: User should add rows
                DataRow row = _testData.NewRow();
                row["Name"] = "John Smith";
                row["Department"] = "Accounting";
                _testData.Rows.Add(row);

                // Initialize combo boxes
                List departmentComboBoxList = new List() {"Accounting", "Purchasing", "Engineering"};
                _Departments.ItemsSource = departmentComboBoxList;
            }
        }
    }


Any thoughts are appreciated. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疯到世界奔溃 2024-09-11 19:49:33

是否显示“新项目占位符”行?因为如果是的话,那就是导致输出绑定错误的原因。

占位符项的数据上下文是一个空对象 - 它自然不具有其他行的属性。

所以,一切都很好 - 如果您多次收到相同的消息(每行一个,然后占位符一个),您就会遇到麻烦:)。

Is the 'New item placeholder' row shown? Because if it is, that's the one causing the output binding error.

The datacontext for a placeholder item is an empty object - which naturally does not have the properties of the other rows.

So, all is good - you are in trouble if you get the same message more than once (one per row and then one for the placeholder) :).

私野 2024-09-11 19:49:33

很难理解你为什么这样做,但我想我可以帮助你理解为什么会出现这个错误。

;
;

您正在绑定到名为 Name 的属性,但如果您遵循代码,您的项目源(在 MyDataGrid 中)将指向 MyDataMyData 不会出现在 MyDataGrid UserControl 内的任何位置。

您拥有的是一个名为 TestData 的属性,但也不起作用,因为
TestData 没有名为 Name 的属性

在我看来,您应该忘记数据表和所有这些内容,并简单地创建对象,将它们放入列表中,使用该列表作为您的数据源,仅此而已。

华泰

It's hard to understand why you are doing this, but I think I can help you understand why is giving you that error.

<toolkit:DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<toolkit:DataGridComboBoxColumn Header="Department" x:Name="_Departmens" SelectedItemBinding="{Binding Department}"/>

You are binding to a property named Name but if you follow the code your items sources (in MyDataGrid) points to MyData. MyData does not appears anywhere inside the MyDataGrid UserControl.

What you have is a property named TestData but won't work either because
TestData does not have a property named Name

In my opinion you should forget about data tables and all that stuff and simple create your objects, put them inside a List, uses that list as your data sources and that's it.

HTH

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文