【问题标题】:CollectionViewSource in WPF not displaying data from DataTableWPF 中的 CollectionViewSource 不显示来自 DataTable 的数据
【发布时间】:2021-06-04 11:06:34
【问题描述】:

DataTable 中的数据未填充 ComboBox 或 TextBox。来自 SQL Server 数据库的数据用于填充 DataTable,它工作正常,我认为 CollectionViewSource 也可以,但没有显示与显示元素的绑定。

我最初通过 TableAdapter 设计器创建了视图,一切正常,数据显示出来了,我可以在表格行中移动。我需要为与数据源的 SQL 连接编写代码,因此我创建了一个 SQL 数据适配器,使用它来填充数据集,然后从该数据集创建一个数据表。通过调试器,我可以看到 DataTable(“compDataTable”)包含所有数据。然后我使用这个 DataTable 作为 CollectionViewSource ('tbl_CompsViewSource') 来绑定到我的 View 控件,就像原来的 TableAdapter 一样,但是当我运行它时,View 控件是空白的。我尝试通过 System.Diagnostics 调试绑定,但它没有显示任何错误,除非它尝试填充视图控件。抛出的错误是:

System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“Char”(HashCode=4325442)上找不到“名称”属性。绑定表达式:路径=名称; DataItem='Char' (HashCode=4325442);目标元素是 'ComboBox' (Name='nameComboBox');目标属性是“NoTarget”(类型“对象”)

System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“EnumerableCollectionView”(HashCode=28278595)上找不到“值”属性。绑定表达式:路径=值; DataItem='EnumerableCollectionView' (HashCode=28278595);目标元素是'TextBox'(名称='valueTextBox');目标属性是“文本”(类型“字符串”)

XML 代码是:

<Window x:Class="CompsTabAdapt.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:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
    Title="MainWindow" Loaded="Window_Loaded">
<Window.Resources>
    <CollectionViewSource x:Key="tbl_CompsViewSource" Source="{Binding Source=compDataTable}" diag:PresentationTraceSources.TraceLevel="High"/>
</Window.Resources>

<StackPanel DataContext="{Binding tbl_CompsViewSource}">
    <Label Content="Compound :"/>
    <ComboBox x:Name="nameComboBox" DisplayMemberPath="Name" ItemsSource="{Binding}" IsEditable="True">
        <ComboBox.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel/>
            </ItemsPanelTemplate>
        </ComboBox.ItemsPanel>
    </ComboBox>
    <StackPanel Orientation="Horizontal">
        <Label Width="120">Value: </Label>
        <TextBox x:Name="valueTextBox" Text="{Binding Value, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/>
    </StackPanel>
</StackPanel>
</Window>

后面的代码是:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace CompsTabAdapt
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    SqlDataAdapter CompsDataAdapt = new SqlDataAdapter();
    DataSet compDataSet = new DataSet();
    DataTable compDataTable = new DataTable();
    CollectionViewSource tbl_CompsViewSource = new CollectionViewSource();


    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            string dbcon = ConfigurationManager.ConnectionStrings["ConnOrigString"].ConnectionString;
            using (SqlConnection Connection = new SqlConnection(dbcon))
            {
                Connection.Open();
                CompsDataAdapt = new SqlDataAdapter("SELECT * FROM tbl_Comps", Connection);
                CompsDataAdapt.Fill(compDataSet);
                Connection.Close();
                compDataTable = compDataSet.Tables[0];
            }
        }
        catch
        {
            dbConnect();
        }
        finally
        {
            tbl_CompsViewSource = (CollectionViewSource)(this.FindResource("tbl_CompsViewSource"));
            tbl_CompsViewSource.View.MoveCurrentToFirst();
        }
}
}

【问题讨论】:

    标签: wpf datatable binding collectionviewsource


    【解决方案1】:

    System.Windows.Data Error: 40 : BindingExpression path error: 'Value' property not found on 'object' ''EnumerableCollectionView' (HashCode=28278595)'. BindingExpression:Path=Value; DataItem='EnumerableCollectionView' (HashCode=28278595); target element is 'TextBox' (Name='valueTextBox'); target property is 'Text' (type 'String') 此消息告诉您的是,它没有在名为“valueTextBox”的文本框的绑定源上找到属性Value。 查看 xaml &lt;TextBox x:Name="valueTextBox" Text="{Binding Value, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/&gt; 没有为绑定定义源,因此源将是它的数据上下文(或者在这种情况下,是具有设置数据上下文的第一个父级的数据上下文)。这是堆栈面板

    <Window.Resources>
         <CollectionViewSource x:Key="tbl_CompsViewSource" Source="{Binding Source=compDataTable}" diag:PresentationTraceSources.TraceLevel="High"/>
    </Window.Resources>
    
    <StackPanel DataContext="{Binding tbl_CompsViewSource}">
    

    所以来源是compDataTable,它在后面的代码中定义(您可能应该明确设置访问修饰符,看到它可以访问我很惊讶)。

    在后面的代码中,我可以看到compDataTable = compDataSet.Tables[0]; 所以compDataTableTable 类型,但是Table 类型没有名为Value 的属性,所以绑定失败。

    关于另一个错误,您将 compDataTable 视为一个集合并尝试访问其中一个项目的 Name 属性,这当然会失败。

    我的猜测是你打算访问这个表的行,所以你应该检查this link,它有一个如何访问数据的例子。

    foreach(DataTable table in dataSet.Tables)
    {
        foreach(DataRow row in table.Rows)
        {
            foreach (DataColumn column in table.Columns)
            {
                //Add it to a list instead and bind the list
                Console.WriteLine(row[column]);
            }
        }
    }
    

    *链接中的示例

    【讨论】:

    • 似乎有很多文章声称 DataTable 本身是有效的绑定源,列名作为属性有效。当我最初通过创建 TableAdapter 来设置绑定时,绑定都有效。在错误消息中。 'Name' 和 'Value' 属性都是有效的表列,尽管基础 'Value' 列中的数据是浮点数而不是文本 (char)。
    • 也许可以链接其中一篇文章,以便我可以向您展示如何根据您的情况调整语法,因为现在它不正确并且您不能直接绑定到 DataTable 对象,也许您弄错了它是为 DataTable.DefaultView DataView 而不是?即使有可能,在您的绑定中,Name 属性以源项目的属性为目标,而 Value 以源项目的属性为目标,因此它不可能是正确的。 (在c#中写this.valueTextBox.Text = compDataTable.Value;也是一样)
    • 在后面的代码中尝试一下,您将收到一条消息,告诉您DataTable doesn't have a property name 'Value',这与您在绑定中获得的很接近,除了 DataTable 不是集合,因此之前的绑定不会也可以按预期工作。检查this answer它可能会消除混乱。
    猜你喜欢
    • 2016-03-15
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多