0
我是新來WPF MVVM我創建動態grid.my代碼如下不能創建動態網格
public class Property : INotifyPropertyChanged
{
public Property(string name, object value)
{
Name = name;
Value = value;
}
public string Name { get; private set; }
public object Value { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
public class Record
{
private readonly ObservableCollection<Property> properties = new ObservableCollection<Property>();
public Record(params Property[] properties)
{
foreach (var property in properties)
Properties.Add(property);
}
public ObservableCollection<Property> Properties
{
get { return properties; }
}
}
public class DataGridColumnsBehavior
{
public static readonly DependencyProperty BindableColumnsProperty =
DependencyProperty.RegisterAttached("BindableColumns",
typeof(ObservableCollection<DataGridColumn>),
typeof(DataGridColumnsBehavior),
new UIPropertyMetadata(null, BindableColumnsPropertyChanged));
private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
DataGrid myDataGrid = source as DataGrid;
ObservableCollection<DataGridColumn> columns = e.NewValue as ObservableCollection<DataGridColumn>;
myDataGrid.Columns.Clear();
if (columns == null)
return;
foreach (DataGridColumn column in columns)
{
myDataGrid.Columns.Add(column);
}
columns.CollectionChanged += (sender, e1) =>
{
-----------// Others stuff
}
private void FillData()
{
List<DataClass> MyClass = new List<DataClass>();
records = new ObservableCollection<Record>();
records.Add(new Record(new Property("FirstName", "Name1"), new Property("LastName", "Name2")));
records.Add(new Record(new Property("FirstName", "Name3"), new Property("LastName", "Name4")));
var columns = records.First()
.Properties
.Select((x, i) => new { Name = x.Name, Index = i })
.ToArray();
ColumnCollection = new ObservableCollection<DataGridColumn>();
foreach (var column in columns)
{
var binding = new Binding(string.Format("Properties[{0}].Value", column.Index));
ColumnCollection.Add(new DataGridTextColumn() { Header = column.Name, Binding = binding });
}
MyClass.Add(new DataClass() { HeaderName = "HeaderVal", GridVal = records });
myListBox.ItemsSource = MyClass;
}
,並在我的主窗口我有
<Grid>
<ListBox Width="400" Margin="10" x:Name="myListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Expander Header="Header1" IsExpanded="False">
<StackPanel>
<DataGrid
x:Name="dataGrid"
local:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}"
AutoGenerateColumns="False"
ItemsSource="{Binding Path=records}"/>
</StackPanel>
</Expander>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
但網格是不可見。我錯過了什麼?
感謝它解決了我的大部分問題,但它正在生成名爲「屬性」的額外列。 – Rohit 2015-03-03 10:46:51