WPF MvvM DataGrid Dynamic Columns - wpf

I am searching about how to create the columns of the DataGrid from the ToolKit dynamic in MvvM way. But looks like it is impossible !
Is there some one that had to do the samething ?
there is no need to create a usercontrol or another control that comes from DataGrid, I just want to set de ItemSource of the grid to my custom object and in some point I want to define the columns of the grid in runtime dynamic based in the kind of the object.
Is that possible ?
cheers

I'm going to preface this by saying it maybe isn't the best solution to be doing and may not work in some situations but you can give it a try and see if it will work for what you want. I just whipped this up so it may have some bugs in it. Its still going to involve some code, but it keeps your model from knowing about you view.
What you need to do is create an extension property that will allow you to bind the Columns property on the DataGrid. Here is an example that I put together.
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
public static class DataGridExtension
{
public static ObservableCollection<DataGridColumn> GetColumns(DependencyObject obj)
{
return (ObservableCollection<DataGridColumn>)obj.GetValue(ColumnsProperty);
}
public static void SetColumns(DependencyObject obj, ObservableCollection<DataGridColumn> value)
{
obj.SetValue(ColumnsProperty, value);
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.RegisterAttached("Columns",
typeof(ObservableCollection<DataGridColumn>),
typeof(DataGridExtension),
new UIPropertyMetadata (new ObservableCollection<DataGridColumn>(),
OnDataGridColumnsPropertyChanged));
private static void OnDataGridColumnsPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if (d.GetType() == typeof(DataGrid))
{
DataGrid myGrid = d as DataGrid;
ObservableCollection<DataGridColumn> Columns =
(ObservableCollection<DataGridColumn>)e.NewValue;
if(Columns != null)
{
myGrid.Columns.Clear();
if (Columns != null && Columns.Count > 0)
{
foreach (DataGridColumn dataGridColumn in Columns)
{
myGrid.Columns.Add(dataGridColumn);
}
}
Columns.CollectionChanged += delegate(object sender,
NotifyCollectionChangedEventArgs args)
{
if(args.NewItems != null)
{
foreach (DataGridColumn column
in args.NewItems.Cast<DataGridColumn>())
{
myGrid.Columns.Add(column);
}
}
if(args.OldItems != null)
{
foreach (DataGridColumn column
in args.OldItems.Cast<DataGridColumn>())
{
myGrid.Columns.Remove(column);
}
}
};
}
}
}
}
Then you attach it to you DataGrid like this (Where columns is the an ObservableCollection property on your view model)
<Controls:DataGrid AutoGenerateColumns="False"
DataGridExtension.Columns="{Binding Columns}" />
I'm not sure how well it is going to respond if you start adding and remove columns, but it seems to work from my basic testing. Good Luck!

Having a similar problem, I did not want to add another dependency property.
My workaround was to organise the data to display in the DataGrid in a DataTable and bind the DataGrid ItemSource property to this DataTable (with of course AutoGenerateColumns set to true).
It works well, DataGrids seem happy with DataTable as source.

I would like to extend the previous example (answer) the ability to subscribe and unsubscribe on event CollectionChanged. Link on my answer in related theme.

Related

Incomplete display of items in combobox wpf c#

I'm using wpf c# and Entity Framework
I have a DataGrid on that show data from database
when users click on datagrid that row will show items in ComboBox (Load on of columns in combobox)
but problem is combobox doesn't show Normal list
Code CS Behind :
DENAF1399Entities dbms = new DENAF1399Entities();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var qre = dbms.Database.SqlQuery<Q_View>("SELECT * FROM Q_View");
datagrid1.ItemsSource = qre.ToList();
}
private void datagrid1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Q_View QVkala = datagrid1.SelectedItem as Q_View;
if (QVkala != null)
{
combobox1.ItemsSource = QVkala.NAMES;
}
}
I tried
-Change Fonts of combobox
-use new combobox
but didn't work
please help me
Edit during formation: It just became obvious to me what's going on. Q_View.NAMES is a string, and by setting combobox1.ItemsSource to that property, it's identifying the individual items as characters in the string (as string is an IEnumerable<char>).
If what you want in the combo box is what's in each of the columns of the selected item, then the way to do that is like this:
private void datagrid1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Q_View QVkala = datagrid1.SelectedItem as Q_View;
if (QVkala != null)
{
object[] items = { QVkala.CODE, QVkala.NAME, QVkala.NAMES, QVkala.TOZIH } //etc whatever properties you want to project into this
combobox1.ItemsSource = items;
}
}
ORIGINAL WORK ON AN ANSWER
At first glance it looks like your data is transposed, but altogether it looks like you aren't using WPF or Entity Framework like you really could be using them. WPF was made for MVVM design and Entity Framework was made for treating tables like collections of objects. Not knowing much else about your application, here's how I'd get started:
First, I'd move basically everything except what's auto-generated out of MainWindow.xaml.cs, and start a new separate class. (Note: may have compiler errors as this is completely off the cuff)
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged; //MainWindow.xaml will hook into this
public ObservableCollection<Q_View> Q_Views { get; private set; }
private Q_View selectedQView;
public Q_View SelectedQView
{
get => selectedQView;
set
{
if(value != selectedQView)
{
selectedQView = value;
PropertyChanged?.Invoke("SelectedQView");
}
}
}
}
And then in MainWindow.xaml.cs, the only change from what's generated would be the constructor (there's another way to do this even without changing the code-behind but I'll not get into it here since I'm not as xaml-adept as I am with C#)
public class MainWindow : Window
{
public MainWindow()
{
DataContext = new MainWindowViewModel();
InitializeComponent(); //that's auto-generated
}
}
And finally, the xaml for your DataGrid. Edit it like this:
<DataGrid Name="QViewDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding Q_Views}" SelectedItem="{Binding SelectedQView}">
<DataGrid.Columns>
<DataGridTextColumn Header="CODE" Binding="{Binding Path="CODE"}"> //and so forth with more columns
</DataGrid.Columns>
</DataGrid>
ComboBox will have a similar syntax for binding an ItemsSource and SelectedItem. Doing this enables you to avoid having event handlers and dealing with boiler plate for updating so many things.

Creating property for WPF user control datagrid

I have a user control with a datagrid called IGrid. I want to add GridViewColumnCollection poperty for it.
public class DataGridNumericColumn : DataGridTextColumn
{
protected override object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs)
{
TextBox edit = editingElement as TextBox;
edit.PreviewTextInput += OnPreviewTextInput;
return base.PrepareCellForEdit(editingElement, editingEventArgs);
}
void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
try
{
Convert.ToInt32(e.Text);
}
catch
{
e.Handled = true;
}
}
}
From Google i got a piece of code `
private Collection<DataGridColumn> field = new Collection<DataGridColumn>();
[Category("Data")]
[Description("Column Creation")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Collection<DataGridColumn> Columns
{
get { return field; }
}
Here I can get GridViewColumnCollection in visual tree ,
My question is how to add a new type (DataGridNumericColumn )in the collection using the above code.
If you do not know what the code does, it is probably best to research it before attempting to use it or come up with your own solution. As far as I can tell, you are attempting to add an additional property to a UserControl that inherits DataGrid.
You have two options:
Create a DependencyProperty (the best choice, in my opinion).
Create a normal property
Here's a couple links to help you get started:
What is the difference between Property and Dependency Property
When should I use dependency properties in WPF?

WPF: Refreshing DataGrid after columns changed in DataTable, MVVM way

I am using vanilla WPF Datagrid that has its ItemsSource bound to a DataTable:
<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding ResultTable.DefaultView}" >
Where ResultTable is the DataTable. I have tried adding rows programmatically at runtime and the DataGrid will update accordingly. However, the DataGrid does not update When I add or remove columns at runtime. Here is what I have in my ViewModel
class MyViewModel : ObservableObject
{
private DataTable resultTable;
public DataTable ResultTable
{
get { return resultTable; }
set
{
resultTable = value;
RaisePropertyChanged("ResultTable");
}
}
public void AddColumn(string columnName)
{
ResultTable.Columns.Add(columnName);
}
}
I found an almost identical question here WPF Datagrid using MVVM.. is two way binding to DataTable possible? but there did not seem to be a conclusive answer. Unfortunately, the person who asked the question seemed to have found a workaround but did not bother to post it...
I also found a solution here http://www.mikeware.com/2012/08/datagrid-dilemma/ but it appears very "hackish" (not to mention non-MVVM) and the author himself admits that he would prefer to do it another way if he found one.
How can I force the DataGrid to update when I add new columns? I prefer to do it in a MVVM way if possible.
First add this code to ViewModel:
private static readonly DataTable _dt = new DataTable();
Then you can add that what like this code when you add column:
public void AddColumn(string columnName)
{
var temp = this.ResultTable;
this.ResultTable = _dt;
temp.Columns.Add(columnName);
this.ResultTable = temp;
}

New records added to DataGridView aren't displayed

I have a custom Order class, groups of which are stored in List<Order> and a DataGridView. I think the problem is in my implementation so here's how I'm using it:
In the form enclosing DataGridView (as OrdersDataGrid):
public partial class MainForm : Form
{
public static List<Order> Orders;
public MainForm()
{
// code to populate Orders with values, otherwise sets Orders to new List<Order>();
OrdersDataGrid.DataSource = Orders;
}
Then in another form that adds an Order:
// Save event
public void Save(object sender, EventArgs e) {
Order order = BuildOrder(); // method that constructs an order object from form data
MainForm.Orders.Add(order);
}
From what I can tell from the console this is added successfully. I thought the DataGrid would be updated automatically after this since Orders has changed - is there something I'm missing?
The DataGrid accepts the class since it generates columns from the members.
Since you can't use DataBind on a DataGridView that's uses an object list as it's DataSource here's the solution I found to this:
First replace your List<T> with BindingList<T> - essentially the same thing, except the BindingList acts like DataBind().
Change your T to implement System.ComponentModel.INotifyPropertyChanged:
This involves adding a property:
public event PropertyChangedEventHandler PropertyChanged;
Adding to each variable's set block:
public string Name
{
get { return this.CustomerName; }
set {
this.CustomerName = value;
this.NotifyPropertyChanged("Name");
}
}
And adding another method:
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
Sources: Binding a DataGridView to a Collection, Info on converting List to BindingList
You need to rebind the data on your DataGrid.
Shouldn't you rebind the DataGrid after the underlying data source is updated?
Use the code:
OrdersDataGrid.DataSource = Orders;
OrdersDataGrid.DataBind();
You have to Bind new data to your datagrid using
Gridview1.DataBind();
note that whenever you update some list, which is binded to a gridview or any other presenter list control, it just update the list not gridview.
if you really do not like to rebind your Item use IronPython which provided in .net 3.5

How to bind DataGridColumn.Visibility?

I have an issue similar to the following post:
Silverlight DataGridTextColumn Binding Visibility
I need to have a Column within a Silverlight DataGrid be visibile/collapsed based on a value within a ViewModel. To accomplish this I am attempting to Bind the Visibility property to a ViewModel. However I soon discovered that the Visibility property is not a DependencyProperty, therefore it cannot be bound.
To solve this, I attempted to subclass my own DataGridTextColumn. With this new class, I have created a DependencyProperty, which ultimately pushes the changes to the DataGridTextColumn.Visibility property. This works well, if I don't databind. The moment I databind to my new property, it fails, with a AG_E_PARSER_BAD_PROPERTY_VALUE exception.
public class MyDataGridTextColumn : DataGridTextColumn
{
#region public Visibility MyVisibility
public static readonly DependencyProperty MyVisibilityProperty =
DependencyProperty.Register("MyVisibility", typeof(Visibility), typeof(MyDataGridTextColumn), new PropertyMetadata(Visibility.Visible, OnMyVisibilityPropertyChanged));
private static void OnMyVisibilityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var #this = d as MyDataGridTextColumn;
if (#this != null)
{
#this.OnMyVisibilityChanged((Visibility)e.OldValue, (Visibility)e.NewValue);
}
}
private void OnMyVisibilityChanged(Visibility oldValue, Visibility newValue)
{
Visibility = newValue;
}
public Visibility MyVisibility
{
get { return (Visibility)GetValue(MyVisibilityProperty); }
set { SetValue(MyVisibilityProperty, value); }
}
#endregion public Visibility MyVisibility
}
Here is a small snippet of the XAML.
<DataGrid ....>
<DataGrid.Columns>
<MyDataGridTextColumn Header="User Name"
Foreground="#FFFFFFFF"
Binding="{Binding User.UserName}"
MinWidth="150"
CanUserSort="True"
CanUserResize="False"
CanUserReorder="True"
MyVisibility="{Binding Converter={StaticResource BoolToVisibilityConverter}, Path=ShouldShowUser}"/>
<DataGridTextColumn .../>
</DataGrid.Columns>
</DataGrid>
A couple important facts.
The Converter is indeed defined above in the local resources.
The Converter is correct, it is used many other places in the solution.
If I replace the {Binding} syntax for the MyVisibility property with "Collapsed" the Column does in fact disappear.
If I create a new DependencyProperty (i.e. string Foo), and bind to it I receive the AG_E_PARSER_BAD_PROPERTY_VALUE exception too.
Does anybody have any ideas as to why this isn't working?
Here's the solution I've come up with using a little hack.
First, you need to inherit from DataGrid.
public class DataGridEx : DataGrid
{
public IEnumerable<string> HiddenColumns
{
get { return (IEnumerable<string>)GetValue(HiddenColumnsProperty); }
set { SetValue(HiddenColumnsProperty, value); }
}
public static readonly DependencyProperty HiddenColumnsProperty =
DependencyProperty.Register ("HiddenColumns",
typeof (IEnumerable<string>),
typeof (DataGridEx),
new PropertyMetadata (HiddenColumnsChanged));
private static void HiddenColumnsChanged(object sender,
DependencyPropertyChangedEventArgs args)
{
var dg = sender as DataGrid;
if (dg==null || args.NewValue == args.OldValue)
return;
var hiddenColumns = (IEnumerable<string>)args.NewValue;
foreach (var column in dg.Columns)
{
if (hiddenColumns.Contains ((string)column.GetValue (NameProperty)))
column.Visibility = Visibility.Collapsed;
else
column.Visibility = Visibility.Visible;
}
}
}
The DataGridEx class adds a new DP for hiding columns based on the x:Name of a DataGridColumn and its descendants.
To use in your XAML:
<my:DataGridEx x:Name="uiData"
DataContext="{Binding SomeDataContextFromTheVM}"
ItemsSource="{Binding Whatever}"
HiddenColumns="{Binding HiddenColumns}">
<sdk:DataGridTextColumn x:Name="uiDataCountOfItems">
Header="Count"
Binding={Binding CountOfItems}"
</sdk:DataGridTextColumn>
</my:DataGridEx>
You need to add these to your ViewModel or whatever data context you use.
private IEnumerable<string> _hiddenColumns;
public IEnumerable<string> HiddenColumns
{
get { return _hiddenColumns; }
private set
{
if (value == _hiddenColumns)
return;
_hiddenColumns = value;
PropertyChanged (this, new PropertyChangedEventArgs("HiddenColumns"));
}
}
public void SomeWhereInYourCode ()
{
HiddenColumns = new List<string> {"uiDataCountOfItems"};
}
To unhide, you only need to remove the corresponding name from the list or recreate it without the unhidden name.
I have another solution to this problem that uses an approach similar to the "Binding" property that you find on DataGridTextColumn. Since the column classes are DependencyObjects, you can't directly databind to them, BUT if you add a reference to a FrameworkElement that implements INotifyPropertyChanged you can pass a databinding through to the element, and then use a dependency property to notify the Column that the databinding has changed.
One thing to note is that having the binding on the Column itself instead of the Grid will probably mean that you will want to use a DataContextProxy to get access to the field that you want to bind the Visibility to (the column binding will default to the scope of the ItemSource).
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace XYZ.Controls
{
public class ExtendedDataGridTextColumn : DataGridTextColumn
{
private readonly Notifier _e;
private Binding _visibilityBinding;
public Binding VisibilityBinding
{
get { return _visibilityBinding; }
set
{
_visibilityBinding = value;
_e.SetBinding(Notifier.MyVisibilityProperty, _visibilityBinding);
}
}
public ExtendedDataGridTextColumn()
{
_e = new Notifier();
_e.PropertyChanged += ToggleVisibility;
}
private void ToggleVisibility(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Visibility")
this.Visibility = _e.MyVisibility;
}
//Notifier class is just used to pass the property changed event back to the column container Dependency Object, leaving it as a private inner class for now
private class Notifier : FrameworkElement, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Visibility MyVisibility
{
get { return (Visibility)GetValue(MyVisibilityProperty); }
private set { SetValue(MyVisibilityProperty, value); }
}
public static readonly DependencyProperty MyVisibilityProperty = DependencyProperty.Register("MyVisibility", typeof(Visibility), typeof(Notifier), new PropertyMetadata(MyVisibilityChanged));
private static void MyVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var n = d as Notifier;
if (n != null)
{
n.MyVisibility = (Visibility) e.NewValue;
n.PropertyChanged(n, new PropertyChangedEventArgs("Visibility"));
}
}
}
}
}
The datagrid column inherits from DependencyObject instead of FrameworkElement. In WPF this would be no big deal... but in silverlight you can only bind to FrameworkElement objects. So you get the descriptive error message of AG_E_PARSER_BAD_PROPERTY_VALUE when you try.
I don't know how much this will help, but I've run into the lack of dependency property problem with data grid columns myself in my latest project. What I did to get around it, was to create an event in the grid column view model, then when the grid is being assembled in the client, use a closure to subscribe the grid column to the column view model. My particular problem was around width. It starts with the view model class for the grid column, which looks something like this pseudo-code:
public delegate void ColumnResizedEvent(double width);
public class GridColumnViewModel : ViewModelBase
{
public event ColumnResizedEvent ColumnResized;
public void Resize(double newContainerWidth)
{
// some crazy custom sizing calculations -- don't ask...
ResizeColumn(newWidth);
}
public void ResizeColumn(double width)
{
var handler = ColumnResized;
if (handler != null)
handler(width);
}
}
Then there's the code that assembles the grid:
public class CustomGrid
{
public CustomGrid(GridViewModel viewModel)
{
// some stuff that parses control metadata out of the view model.
// viewModel.Columns is a collection of GridColumnViewModels from above.
foreach(var column in viewModel.Columns)
{
var gridCol = new DataGridTextColumn( ... );
column.ColumnResized += delegate(double width) { gridCol.Width = new DataGridLength(width); };
}
}
}
When the datagrid is resized in the application, the resize event is picked up and calls the resize method on the viewmodel the grid is bound to. This in turn calls the resize method of each grid column view model. The grid column view model then raises the ColumnResized event, which the data grid text column is subscribed to, and it's width is updated.
I realise this isn't directly solving your problem, but it was a way I could "bind" a view model to a data grid column when there are no dependency properties on it. The closure is a simple construct that nicely encapsulates the behaviour I wanted, and is quite understandable to someone coming along behind me. I think it's not too hard to imagine how it could be modified to cope with visibility changing. You could even wire the event handler up in the load event of the page/user control.
Chris Mancini,
you do not create binding to "Binding" property of data grid column. Well, you write "{Binding User.UserName}", but it doesn't create binding, because (as zachary said) datagrid column doesn't inherit from FrameworkElement and hasn't SetBinding method.
So expression "{Binding User.UserName}" simply creates Binding object and assign it to Binding property of column (this property is type of Binding).
Then datagrid column while generates cells content (GenerateElement - protected method) uses this Binding object to set binding on generated elements (e.g. on Text property of generated TextBlock) which are FrameworkElements
GreatTall1's solution is great, but it need to bit change to make it work.
var n = d as Notifier;
if (n != null)
{
//Assign value in the callback will break the binding.
//n.MyVisibility = (Visibility)e.NewValue;
n.PropertyChanged(n, new PropertyChangedEventArgs("Visibility"));
}
Note that the problem isn't just as simple as 'Visibility' not being a dependency property. In a DataGrid the columns aren't part of the visual 'tree' so you can't use AncestorType even in WPF (or Silverlight 5).
Here's a couple WPF related links (please comment if any of these work for Silverlight - sorry I don't have time to test now)
Has a really nice explanation of the problem and failures of certain solutions (and a clever solution):
http://tomlev2.wordpress.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
And a couple StackOverflow questions:
WPF Hide DataGridColumn via a binding
Binding Visible property of a DataGridColumn in WPF DataGrid
This works on a data grid template column:
public class ExtendedDataGridColumn : DataGridTemplateColumn
{
public static readonly DependencyProperty VisibilityProperty = DependencyProperty.Register("Visibility", typeof(Visibility), typeof(DataGridTemplateColumn), new PropertyMetadata(Visibility.Visible, VisibilityChanged));
public new Visibility Visibility
{
get { return (Visibility)GetValue(VisibilityProperty); }
set { SetValue(VisibilityProperty, value); }
}
private static void VisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((DataGridTemplateColumn)d != null)
{
((DataGridTemplateColumn)d).Visibility = (Visibility)e.NewValue;
}
}
}
From your MyDataGridTextColumn class, you could get the surrounding DataGrid.
Then you get your ViewModel out of the DataContext of the DataGrid and add a handler to the PropertyChanged event of your ViewModel. In the handler you just check for the property name and its value and change the Visibility of the Column accordingly.
Its not quite the best solution, but it should work ;)

Resources