简体   繁体   English

datatable作为wpf中datagrid的项源

[英]datatable as an itemsource for datagrid in wpf

How can I set a datagrid control values from a datatable ? 如何设置数据表中的数据网格控件值?

I use this source 我用这个来源

    public static readonly DependencyProperty ObjDataTableDefaultViewProperty = DependencyProperty.Register("ObjDataTableDefaultView", typeof(System.Data.DataView), typeof(Window1), new FrameworkPropertyMetadata());

    public System.Data.DataView ObjDataTableDefaultView
    {
        get { return (System.Data.DataView)GetValue(ObjDataTableDefaultViewProperty); }
        set { SetValue(ObjDataTableDefaultViewProperty, value); }
    }
    private void CreateObjDataTable()
    {
        try
        {
            ObjDataTableDefaultView = table.DefaultView;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

But it has got an error message and the program stops, 但是出现错误消息,程序停止,

A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll PresentationFramework.dll中发生类型为'System.Windows.Markup.XamlParseException'的第一次机会异常

Additional information: Cannot create instance of 'Window1' defined in assembly 'ReadSky, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. 附加信息:无法创建在程序集'ReadSky,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'中定义的'Window1'实例。 Exception has been thrown by the target of an invocation. 调用的目标已引发异常。 Error in markup file 'Window1.xaml' Line 1 Position 9. 标记文件“ Window1.xaml”的第1行第9位错误。

 My XAML

<Window x:Class="ReadSky.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="296" Width="738" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit">
    <Grid>
        <my:DataGrid AutoGenerateColumns="False" Margin="36,30,39,90" Name="gridCtrl" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" IsReadOnly="True" RowBackground="Gray" AlternatingRowBackground="White" ItemsSource="{Binding ObjDataTableDefaultView, ElementName=uc, Mode=OneWay}"/>
    </Grid>
</Window>

You could try this: 您可以尝试以下方法:

 <DataGrid Name="grid" AutoGenerateColumns="True" ItemsSource="{Binding}" />     

 public DataTable TableData {
        get {
            DataTable dt = new DataTable();
            dt.Columns.Add("col1");
            dt.Columns.Add("col2");
            dt.Rows.Add(new string[] {"val1", "val2"});
            return dt;
        }
    }

 grid.DataContext = TableData;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM