【发布时间】: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