Datagrid有多个bug;
1,不支持DynamicResource的东西
2, 在Column隐藏后再显示, ColumnHeader的Tag或者DataContext为null。
解决办法:
用StaticResource ,如下面的
StaticResource
DGC_ContentTemplate;
用DataGridColumnHeader的Column,来取得上层的datacontext。如,
ItemsSource
="{
Binding
Path
=Column.Tag,
Converter
={
StaticResource
DebugConverter
},
Mode
=OneWay,
RelativeSource
={
RelativeSource
FindAncestor
,
AncestorType
={
x
:
Type
DataGridColumnHeader
}}}"
private void InitDataGridBinding (DataGridColumnEx col, string path)
{
if (null == col || String.IsNullOrWhiteSpace (path) || null == col .Header)
{
return;
}
Binding binding = new Binding();
binding.Mode = BindingMode. OneWay;
binding.RelativeSource = new RelativeSource(RelativeSourceMode .Self);
binding.Converter = new BoolToVisibilityConverter();
binding.Path = new PropertyPath("(FrameworkElement.DataContext).PACfgVM." + path + ".CfgInfo[" + PAAttachedProperty. GetName(col ) + "].IsVisiable");
BindingOperations.SetBinding (col, DataGridColumnEx.VisibilityProperty , binding);
//{for combobox binding in columnHeader
col.Tag = PAAttachedProperty. GetTag(col );
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor .FromProperty( DataGridColumnEx.VisibilityProperty , typeof(DataGridColumnEx ));
if (dpd != null)
{
dpd.AddValueChanged (col, delegate
{
//
InitDataGridColumnHeader(col , GetDataGridParent( col));
});
}
//}
}
<DataTemplate x :Key="DGC_ContentTemplate">
<TextBlock TextWrapping ="Wrap" Text="{ Binding }" MinWidth ="20"/>
DataTemplate>
<
Style
x
:
Key
="DataGridColumnHeaderStyle_ComboBox"
TargetType
="{
x
:
Type
DataGridColumnHeader
}">
<
Setter
Property
="ContentTemplate"
Value
="{
StaticResource
DGC_ContentTemplate
}"/>
<
Setter
Property
="VerticalContentAlignment"
Value
="Center"/>
<
Setter
Property
="Template">
<
Setter.Value
>
<
ControlTemplate
TargetType
="{
x
:
Type
DataGridColumnHeader
}">
<
Grid
>
<
StackPanel
Orientation
="Vertical"
d
:
LayoutOverrides
="Height"
Margin
="10">
<
Label
Foreground
="Black"
HorizontalContentAlignment
="Left"
Content
="{
TemplateBinding
Content
}"/>
<
ComboBox
Margin
="0,10,0,0"
ItemsSource
="{
Binding
Path
=Column.Tag,
Converter
={
StaticResource
DebugConverter
},
Mode
=OneWay,
RelativeSource
={
RelativeSource
FindAncestor
,
AncestorType
={
x
:
Type
DataGridColumnHeader
}}}">
ComboBox
>
StackPanel
>
<
Thumb
x
:
Name
="PART_LeftHeaderGripper"
HorizontalAlignment
="Left"
Style
="{
StaticResource
ColumnHeaderGripperStyle
}"/>
<
Thumb
x
:
Name
="PART_RightHeaderGripper"
HorizontalAlignment
="Right"
Style
="{
StaticResource
ColumnHeaderGripperStyle
}"/>
Grid
>
ControlTemplate
>
Setter.Value
>
Setter
>
<
EventSetter
Event
="Selector.SelectionChanged"
Handler
="ComboBox_SelectionChanged"/>
Style
>