WPF将DataTable列绑定到文本框

时间:2011-08-30 16:45:56

标签: c# wpf data-binding textbox datatable

我开始使用WPF并发现很难获得最简单的绑定工作。这是一些让步......

我有一个查询现有数据库并返回“datatable”对象的对象,数据返回(出于测试目的,只有一行和一列称为“MyTextColumn”)

数据表不是“强类型”,因为我在其他地方读过试图强制强类型对象的问题。我想从代码隐藏的角度来理解底层机制,而不是从XAML的角度来理解。从阅读,显然你不能直接绑定到数据表,但你可以到DataTable对象的“DefaultView”(对我来说没有意义,因为他们指向相同的记录(或记录集,除了说一个某种类型的过滤器。)

因此,在窗口的XAML部分中,

<src:MyWindow blah, blah >
  <Grid Name="grdTesting">
    <Grid.RowDefinitions>
      <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition />
      <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <Label Name="lblMyTextColumn" 
        Content="Just the label" 
        Grid.Row="0" Grid.Column="0 "/>

    <TextBox Name="txtMyTextColumn"
        Grid.Row="0" Grid.Column="1"
        Width="120" />
  </Grid>
</src:MyWindow>

所以现在,我在代码隐藏中,我读过的是你必须有一个BindingListCollectionView oView;

public partial class MyWindow : Window
{
  BindingListCollectionView oView;
  MyQueryingManager oTestMgr;

  public MyWindow()
  {
    InitializeComponent();

    oTestMgr = new MyQueryingManager();
    DataTable oResults = oTestMgr.GetTheData();

    // Data context for the form bound to the Table retrieved
    oView = new BindingListCollectionView( oResults.DefaultView );

    // One place said the Window should get the binding context
    DataContext = oView;

    // another indicated the grid...  Just need to know which I SHOULD be using
    grdTesting.DataContext = oView;


    // Now, for my binding preparation...
    Binding bindMyColumn = new Binding();
    bindMyColumn.Source = oView;
    bindMyColumn.Path = new PropertyPath("MyTextColumn");
    txtMyTextColumn.SetBinding( TextBox.TextProperty, bindMyColumn );
  }
}

所以...我在这里缺少什么...应该简单,没有什么复杂的,我有一个数据表,有一个记录,有一个值。运行表单(无论绑定上下文到窗口还是网格),记录值不会显示在文本框控件中。一旦我理解了单个文本框上的行为,我就可以继续使用所有其他元素(验证,输入掩码,格式化等),但是我在这个元素的门口就被卡住了。

由于

3 个答案:

答案 0 :(得分:1)

首先,您可以绑定到DataTable,但也可以使用默认视图(DataView)等。

通常,您将DataTable绑定到ItemsControl或从中派生的控件,例如ListBoxDataGrid等。然后每个容器都会获得{ {1}}(或DataRow),绑定很容易。

由于您将其直接绑定到DataRowView内的TextBox,因此您必须在绑定中同时指定GridRow。绑定到第一行中名为“MyTextColumn”的列的正确路径为Column

试试这个

Rows[0][MyTextColumn]

如果您直接绑定到Binding bindMyColumn = new Binding(); bindMyColumn.Source = oResults; bindMyColumn.Path = new PropertyPath("Rows[0][MyTextColumn]"); txtMyTextColumn.SetBinding(TextBox.TextProperty, bindMyColumn); ,则问题在于它没有实现DataTable,因此如果从其他来源更改了值,则UI不会知道该值已更改。在这种情况下,您可以使用INotifyPropertyChanged代替。这里的绑定语法会有所不同,因为您直接使用索引运算符访问DataView

DataRowViews

答案 1 :(得分:0)

网格只是一个布局面板(想想电子表格)。您必须手动将控件放入单元格中。

您正在寻找的可能是 DataGrid ,它可以使用反射自动生成列(或者您可以自己定义列)。如果您不想使用众多第三方数据网格控件中的一个,WPF Toolkit from Microsoft就可以使用。

答案 2 :(得分:0)

您正在使用Grid作为布局控件,这意味着它具有可视元素作为子元素,而不是项目。例如,您应该像Listbox一样使用ItemsControl,并将ItemsSource属性绑定到您的集合。