Binding Values to DataGridTemplateColumns in codebehind

Sep 15, 2009 at 1:43 PM

I am having some problems with the DataGrid. We are saving some user settings while the user works with our application. These settings contain the DisplayIndex of the columns that are visible in the DataGrid. The big problem is, that those settings can be changed at runtime. While the settings change it may happen that a DisplayIndex is set that already exists in the existing columns. So the app crashes.

My idea is to remove all columns before new settings are loaded an recreate them when the new settings are loaded. But I am having some problems with this too :-(

Here is what I have been doing in Xaml:

<TK:DataGridTemplateColumn  Header="Wertstellung" IsReadOnly="True"
                            CanUserSort="True" SortMemberPath="Valuta"
                            Width="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(FrameworkElement.DataContext).ActiveSettings.Wertstellung.Width, Converter={StaticResource DoubleToDataGridLengthConverter}, Mode=TwoWay}"
                                         Visibility="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(FrameworkElement.DataContext).ActiveSettings.Wertstellung.IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"

I wanted to do the same in code behind but somehow I can't set Bindings on the WidthProperty in codebehind...

//aktive Settings
            BuchungViewModel model = DataContext as BuchungViewModel;

            DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
            templateColumn.Header = "";
            templateColumn.IsReadOnly = false;
            templateColumn.CanUserSort = false;

            Binding split1 = new Binding("ActiveSettings.SplitbuchungVisibility.Width");
            split1.Source = model;

            templateColumn.CellTemplate = Resources["SplitbuchungTemplateColumn"] as DataTemplate;
templateColumn.Width. ???

Is there a way to achieve what I want?

Sep 22, 2009 at 8:49 AM

Is there no way to do that? I still need a way to recreate items from code behind...

Sep 22, 2009 at 9:59 PM

Hi Woggly,

In order to setup the DataGridTemplateColumn binding, you should use static method BindingOperations.SetBinding.  Please visit the link posted below for guidance.


Saied K.

Sep 23, 2009 at 6:58 AM

Hi Saied!

Thank you for your answer! I found out that it is working this way yesterday, brfore I read your answer. This way it works like I wanted!