【问题标题】:How can I bind all the tables in a DataSet to a DataGrid如何将 DataSet 中的所有表绑定到 DataGrid
【发布时间】:2018-10-08 13:04:26
【问题描述】:

我正在尝试将DataSet 中的每个表绑定到它们自己的DataGrid,但我不确定我该怎么做,这是我尝试过的:

<ListView ItemsSource="{Binding CalibrationData.CalibrationValuestoWrite}">

    <DataGrid ItemsSource="{Binding}">
    </DataGrid>

</ListView>

也许我需要创建一个DataTemplate?非常感谢任何帮助!

【问题讨论】:

  • 您只能将ItemsSource 属性绑定到IEnumerableCalibrationData.CalibrationValuestoWrite 是什么?

标签: c# wpf xaml datagridview


【解决方案1】:

试试这个希望对你有帮助

<DataGrid AutoGenerateColumns="False" Height="250" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="12,40,0,0" Name="mytbl" VerticalAlignment="Top" Width="479">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Col1" Width="50" />
                <DataGridTextColumn Header="Col2" Width="375"/>
                <DataGridTextColumn Header="Col3" Width="50"/>
            </DataGrid.Columns>
        </DataGrid>

背后的代码

this.mytbl.DataContext = ds.Tables[0].DefaultView; 

【讨论】:

  • 仅供参考:您不需要在任何关于他们自己问题的内容中标记 OP,因为他们会自动收到任何已发布的 cmets、答案等的通知。
【解决方案2】:

您只能将ItemsSource 属性绑定到IEnumerable。并且您定义一个ItemTemplate 来定义可枚举返回的每个项目的外观。

因此,如果CalibrationData.CalibrationValuestoWrite 返回一个IEnumerable&lt;DataTable&gt;DataSet.Tables 属性确实如此)并且您想为每个DataTable 显示一个DataGrid,这应该可以:

<ListView ItemsSource="{Binding CalibrationData.CalibrationValuestoWrite.Tables}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <DataGrid ItemsSource="{Binding}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

【讨论】:

  • 我使用过这种方法,我发现它是一种利用ListView 的非常灵活的方法,但仍然可以从中获得“真正的网格”的感觉。
  • 哦,好吧,你知道我如何将DataSet 转换为IEnumerable&lt;DataTable&gt; 吗?
  • @Alfie:绑定到DataSetTables 属性。
  • 我刚刚尝试过,使用您上面给出的示例,但遗憾的是它似乎不起作用
  • @Alfie:只要绑定到 DataSet 属性确实有效,它就应该有效。确保您已正确设置 DataContext。
【解决方案3】:

最好像这里的这个小示例中那样与 DataView 绑定:

(vm 是 XAML 视图的数据上下文)。

XAML:

<DataGrid ItemsSource="{Binding MyGrid}">
</DataGrid>

C#,视图模型

    public partial class vm : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;
      protected void OnPropertyChanged(string text)
      {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(text));
        }
      } 

      public vm()
      {
        DataTable dt;

        ...

        MyGrid = new DataView(dt);
      }

      private DataView _mygrid;
      public DataView MyGrid
      {
         get
         {
            return _mygrid;
         }
         set
         {
            _mygrid= value;
            OnPropertyChanged("MyGrid");
         }
      }
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-06
    • 2010-12-24
    • 2012-05-25
    • 2011-10-12
    • 2014-01-13
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    相关资源
    最近更新 更多