我将ObservableCollection绑定到Datagrid。除了这个行高问题,一切都在工作我现在已经打了一段时间了。
问题是行高是存储最大单元格的高度而不是从那里改变。
如果我有5个对象的集合。在ASC顺序中,第1行高度为100,第5行高度为20.如果我将相同列移至DESC,则第1行高度现在为100,第5行高度为100。
我尝试在Scrollviewer中包装Datagrid,并使用垂直对齐的文本框将DataGridTextColumn更改为DataGridTemplateColumn。 Silverlight没有ViewCollectionSource,所以我无法尝试那个。
如何在排序后重新计算高度?
XAML
SelectedItem="{Binding SelectedComment, Mode=TwoWay}"
VerticalAlignment="Top"
Width="1000"
Height="Auto"
>
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header ="Comment" Width="4*" IsReadOnly="True" SortMemberPath="Commentstr" CanUserSort="True">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Commentstr}" TextWrapping="Wrap" VerticalAlignment="Top"></TextBlock>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
代码隐藏
private ObservableCollection<Comment> commentCollection = new ObservableCollection<Comment>();
public ObservableCollection<Comment> CommentCollection
{
get { return commentCollection; }
set
{
commentCollection = value;
}
}
public Main()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(CustomScreenTemplate_Loaded);
CommentGrid.ItemsSource = CommentCollection;
}
答案 0 :(得分:0)
最后解决了行高问题。发布对我有用的内容,以防其他人遇到同样的问题。
为DataGrid创建覆盖类
public class FixedDataGrid : DataGrid
{
/// <summary>
/// Overrides OnLoadingRow
/// </summary>
protected override void OnLoadingRow(DataGridRowEventArgs e)
{
if (double.IsNaN(this.RowHeight))
{
e.Row.Loaded += Row_Loaded;
}
base.OnLoadingRow(e);
}
private void Row_Loaded(object sender, RoutedEventArgs e)
{
var row = (DataGridRow)sender;
row.Loaded -= Row_Loaded;
for (int col = 0; col < this.Columns.Count; col++)
{
var cellElement = this.Columns[col].GetCellContent(row);
if (cellElement != null)
{
cellElement.SizeChanged += CellElement_SizeChanged;
}
}
}
private static void CellElement_SizeChanged(object sender, SizeChangedEventArgs e)
{
//Fix issue: DataGrid Row Auto-Resize only grows row height but won't shrink
var dataGrid = GetParentOf<DataGrid>((FrameworkElement)sender);
if (dataGrid != null && double.IsNaN(dataGrid.RowHeight))
{
var row = DataGridRow.GetRowContainingElement((FrameworkElement)sender);
//Fore recalculating row height
try
{
dataGrid.RowHeight = 0;
row.InvalidateMeasure();
row.Measure(row.RenderSize);
}
finally
{
//Restore RowHeight
dataGrid.RowHeight = double.NaN;
}
}
}
private static T GetParentOf<T>(FrameworkElement element) where T : FrameworkElement
{
while (element != null)
{
T item = element as T;
if (item != null)
{
return item;
}
element = (FrameworkElement)VisualTreeHelper.GetParent(element);
}
return null;
}
}
使用override类作为Datagrid
xmlns:fixed="clr-namespace:MyNameSpace
<fixed:FixedDataGrid x:Name="BetterGrid" ... />