I have a MultiColumn TreeView which uses a GridViewColumnCollection. I my situation, I don't know how many columns will be there, nor their header names. That's discovery at run time.
Hence I have need to create these columns in code and bind dynamically to them.
Okay - creation is simple enough:
GridViewColumn c = new GridViewColumn();
c.Header = "Next Column";
myTree.Columns.Add(c);
Now where I stumble - Suppose I wish to bind to my viewModel's "MyName" property:
Binding myBinding = new Binding(??);
myBinding.Source = ??
BindingOperations.SetBinding(myTree,GridViewColumn.???? , myBinding);
Now the template for this
<DataTemplate x:Key="CellTemplate_Name">
<DockPanel>
<ToggleButton x:Name="Expander"
Margin="{Binding Level,
Converter={StaticResource LevelToIndentConverter},
RelativeSource={RelativeSource AncestorType={x:Type l:TreeListViewItem}}}"
ClickMode="Press"
IsChecked="{Binding Path=IsExpanded,
RelativeSource={RelativeSource AncestorType={x:Type l:TreeListViewItem}}}"
Style="{StaticResource ExpandCollapseToggleStyle}" />
<TextBlock Text="{Binding Name}" />
.
.
.
<Style TargetType="{x:Type l:TreeListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type l:TreeListViewItem}">
<StackPanel>
<Border Name="Bd"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}">
<GridViewRowPresenter x:Name="PART_Header"
Columns="{Binding Path=Columns,
RelativeSource={RelativeSource AncestorType={x:Type l:TreeListView}}}"
Content="{TemplateBinding Header}" />
</Border>
<ItemsPresenter x:Name="ItemsHost" />
</StackPanel>
Where column insertion and binding in XAML appears as:
<l:TreeListView x:Name="myTree" ItemsSource="{Binding MySource}">
<l:TreeListView.Columns>
<GridViewColumn x:Name="GridViewColumn0" CellTemplate="{StaticResource CellTemplate_Name}"
Header="Name" />
<GridViewColumn Width="60"
DisplayMemberBinding="{Binding Description}"
Header="Description" />
Any help with SetBinding here would be greatly appreciated. I've searched till my fingers fell off.
Update: Excellent answer:
GridViewColumn c = new GridViewColumn();
c.Header = "Next Column";
myTree.Columns.Add(c);
Binding myBinding = new Binding("MyName");
myBinding.Source = viewModel;
BindingOperations.SetBinding(myTree.Columns[myTree.Columns.Count - 1],
GridViewColumn.HeaderProperty,
myBinding);
The binding now works against the Header perfectly - thank you so much.