【问题标题】:Binding List of data to several DataGrid将数据列表绑定到多个 DataGrid
【发布时间】:2016-02-18 00:41:14
【问题描述】:

我在绑定到 DataGrid 的 ViewModel 中有数据。但我需要多个数据并将其动态绑定到多个 DataGrid。

public sealed class ViewModel : INotifyPropertyChanged
{
    private DataTable data;
    public DataTable Data
    {
        get { return data; }
        set { data = value; OnPropertyChanged("Data"); }
    }

    private char[] head;
    public char[] Head
    {
        get { return head; }
        set { head = value; OnPropertyChanged("Head"); }
    }

    private char name;
    public char Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }
    private static readonly ViewModel instance = new ViewModel();

    public static ViewModel Instance
    {
        get { return instance; }
    } 
    private ViewModel()
    {
        data = new DataTable();
    }

    protected void OnPropertyChanged(string propertyName)
    {
        if (null != PropertyChanged)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

我在 XAML 中的数据网格

<DataGrid Name="dtgOutput" Grid.Row="0" Grid.Column="2" AutoGenerateColumns="True" IsReadOnly="True" Width="Auto" Height="Auto" VerticalAlignment="Top"
                  ItemsSource="{Binding Data, diag:PresentationTraceSources.TraceLevel=High}" HeadersVisibility="All">
  <DataGrid.RowHeaderTemplate>
    <DataTemplate>
      <TextBlock Text="Row header" />
    </DataTemplate>
  </DataGrid.RowHeaderTemplate>
  <DataGrid.Resources>
    <Style TargetType="Button" x:Key="{ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}">
      <Setter Property="Content" Value="{Binding Name}" />
    </Style>
  </DataGrid.Resources>
</DataGrid> 

我有一个这样的想法:将任何集合和每个项目绑定到一个 DataGrid。当然,我不知道收藏中会有多少物品。

List<Data> list = new List<Data>;
list.Add(new Data(dataTable, head, name);
list.Add(new Data(dataTable, head, name);

list[0]; //bind to first DataGrid
list[1]; //bind to second DataGrid

有什么想法吗?

【问题讨论】:

    标签: c# wpf mvvm data-binding datagrid


    【解决方案1】:

    不要将数据表绑定到数据网格,而是尝试将其绑定到数据视图。

    DataTable table = new DataTable();
    DataView view = table.DefaultView;
    

    View Model 将包含表格列表和类似的内容:

    dataGrid[0].ItemSource = table[0].DefaultView;
    dataGrid[1].ItemSource = table[1].DefaultView;
    

    上面的也可以移到xaml中。

    现在希望这也可以解决属性更改通知的问题。

    【讨论】:

    • 我不确定这一点,因为我需要将数据、头部和名称等属性绑定到一个 DataGrid。而且我也不知道如何将我的 Head 属性绑定到 DataGrid 的行标题。
    • 我使用 Caliburn.Micro 框架和他的 Conductor.Collection.AllActive 解决了这个问题
    猜你喜欢
    • 2016-04-30
    • 2013-08-06
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多