开发者

Dynamic columns with Silverlight DataGrid

开发者 https://www.devze.com 2022-12-18 00:05 出处:网络
I\'m trying to add columns to a Silverlight DataGrid but having problems. In my View (I\'m using Prism) I can add the columns in the constructor no problem, this works fine -

I'm trying to add columns to a Silverlight DataGrid but having problems. In my View (I'm using Prism) I can add the columns in the constructor no problem, this works fine -

public MyView()
{
   InitializeComponent();
   myDatagrid.Columns.Add(new DataGridCheckBoxColumn() { Header = "HELLO!" });
}

However if I 开发者_运维问答attempt to add a column when the DataContext is set the column is added (I can see Columns.Count increase when debugging) however the new column isn't rendered.

public IMyViewModel ViewModel
{
    get { return DataContext as IMyViewModel ; }
    set
    {
        DataContext = value;
        myDatagrid.Columns.Add(new DataGridCheckBoxColumn() { Header = "HELLO!" });
    }
}

Now, I know this does NOT respect the MVVM paradigm. This is not how I'm intending to write the code however I will need some crappy code like this in the View to set up the columns when the ItemSource that's bound to the DataGrid changes. You see the columns will grow and shrink depending on the user's input and I need to add / remove the columns and set bindings accordingly.

I have also tried the following thinking it was because it wasn't executing on the UI thread -

myDatagrid.Dispatcher.BeginInvoke(() =>
{
    myDatagrid.Columns.Add(new DataGridCheckBoxColumn() { Header = "HELLO!" });
});


I think its probably a bit much to ask of DataGrid to dynamically create new cells when its already displaying data. It might be worth calling UpdateLayout on the DataGrid having added the new column just to see if that convinces it re-layout the cells.

0

精彩评论

暂无评论...
验证码 换一张
取 消