Listview item text truncated after itemssource change
-
16-12-2019 - |
Domanda
I have WPF ListView and MVVM. ListView is a part of simple parent-child structure. Parent is also ListView control. When I change selected item in parent control, ItemsSource for child control is updated. If, for example, in first ItemsSource the longest text of the items contains 5 characters, after changing ItemsSource, every item's text is visible up to 5 characters (in new ItemsSource). How can I override this problem?
Code example:
<ListView Grid.Row="0" Grid.Column="3" ItemsSource="{Binding Tasks}" Width="200" Height="250" VerticalAlignment="Bottom" SelectionMode="Extended">
<ListView.View>
<GridView>
<GridView.ColumnHeaderContainerStyle>
<Style TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="Visibility" Value="Collapsed"/>
</Style>
</GridView.ColumnHeaderContainerStyle>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}" BasedOn="{StaticResource {x:Type ListViewItem}}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
I use BureauBlue theme but anyway, if I don't use it, I have the same problem.
Part of the code in ViewModel:
private void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentParentItem")
{
if (this.CurrentParentItem != null)
{
this.Tasks = GetTasks();//ObservableCollection
}
else
{
this.Tasks = null;
}
}
}
Soluzione
GridView does not recalculate width with a new data. To reset width you can use the following
foreach (GridViewColumn c in gv.Columns)
{
// Code below was found in GridViewColumnHeader.OnGripperDoubleClicked() event handler (using Reflector)
// i.e. it is the same code that is executed when the gripper is double clicked
// if (adjustAllColumns || App.StaticGabeLib.FieldDefsGrid[colNum].DispGrid)
if (adjustAllColumns || fdGridSorted[colNum].AppliedDispGrid)
{
if (double.IsNaN(c.Width))
{
c.Width = c.ActualWidth;
}
c.Width = double.NaN;
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow