我有一个使用 GridViewColumnCollection 的 MultiColumn TreeView。我的情况,我不知道会有多少列,也不知道它们的标题名称。这是运行时的发现。
因此,我需要在代码中创建这些列并动态绑定到它们。
好的 - 创建很简单:
GridViewColumn c = new GridViewColumn();
c.Header = "Next Column";
myTree.Columns.Add(c);
现在我绊倒了 - 假设我希望绑定到我的 viewModel 的“MyName”属性:
Binding myBinding = new Binding(??);
myBinding.Source = ??
BindingOperations.SetBinding(myTree,GridViewColumn.???? , myBinding);
现在这个模板
<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>
XAML 中的列插入和绑定显示为:
<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" />
任何有关 SetBinding 的帮助将不胜感激。我一直在寻找,直到我的手指掉下来。
更新:很好的答案:
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);
绑定现在可以完美地对抗标题 - 非常感谢。