我在数据网格上遇到列宽问题。它们总是截断单元格中文本块的一部分。我有一个转换器,它将文本块的minWidth设置为要显示的字符串的长度,但列坚持截断它。
以下是用于生成DataGridTemplateColumn:的代码
//create template for EDITING text parameters removed for brevity
//create template for SHOWING text parameters
DataTemplate dt2 = new DataTemplate();
FrameworkElementFactory tblk = new FrameworkElementFactory(typeof(TextBlock));
tblk.SetBinding(TextBlock.DataContextProperty, new Binding("doorparameters[" + pid.ToString() + "]"));
tblk.SetResourceReference(TextBlock.StyleProperty, "ParameterStringTextBlockStyle");
tblk.AddHandler(TextBlock.MouseRightButtonUpEvent, new MouseButtonEventHandler(this.StringParameter_MouseRightButtonUp));
FrameworkElementFactory b = new FrameworkElementFactory(typeof(Border));
b.SetResourceReference(Border.StyleProperty, "ParameterStringBorderStyle");
b.AppendChild(tblk);
dt2.VisualTree = b;
DataGridTemplateColumn dgtc = new DataGridTemplateColumn();
dgtc.HeaderStyle = (Style)_myDataGrid.FindResource("ParameterHeaderStyle");
dgtc.Width = DataGridLength.Auto; //SizeToCells is actually worse
dgtc.Header = dp.Name;
dgtc.CellEditingTemplate = dt;
dgtc.CellTemplate = dt2;
_myDataGrid.Columns.Add(dgtc);
以下是xaml中的样式:
<Style x:Key="ParameterStringTextBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="FontFamily" Value="{Binding Source={x:Static properties:Settings.Default}, Path=ScheduleFont.FontFamily.Name}" />
<Setter Property="FontSize" Value="{Binding Source={x:Static properties:Settings.Default}, Path=ScheduleFont, Converter={StaticResource sizeConverter}}" />
<Setter Property="MinHeight" Value="12" />
<Setter Property="Padding" Value="2,0,0,0"/>
<Setter Property="TextAlignment" Value="Left" />
<Setter Property="TextWrapping" Value="NoWrap"/>
<Setter Property="Tag" Value="{Binding Id}" />
<Setter Property="Text" Value="{Binding Value}" />
<Setter Property="Width" Value="Auto"/>
<Setter Property="MinWidth">
<Setter.Value>
<MultiBinding Converter="{StaticResource textwidthconverter}">
<Binding Path="Value" />
<Binding RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsChecked}" Value="True">
<Setter Property="Background" Value="{StaticResource IsCheckedBrush}" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsReadOnly}" Value="True">
<Setter Property="Background" Value="{StaticResource ReadOnlyBrush}" />
</DataTrigger>
<DataTrigger Binding="{Binding Path=HasChanged}" Value="True">
<Setter Property="Background" Value="{StaticResource HasChangedVBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="ParameterStringBorderStyle" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="2" />
<Setter Property="BorderBrush" Value="Black" />
<Setter Property="Width" Value="Auto" />
<Setter Property="MinHeight" Value="12" />
</Style>
我看不出是什么导致列宽截断,但我注意到只有当水平滚动条出现时才会发生这种情况。有什么想法吗?
最终发现必须设置所有DataGridTemplateColumn width=DataGridLength.SizeToCells。有些设置为"auto",这似乎会打乱网格。