我有WPF ListView和MVVM。 ListView是简单父子结构的一部分。 Parent也是ListView控件。当我在父控件中更改所选项时,将更新用于子控件的ItemsSource。例如,如果在第一个ItemsSource中,项目的最长文本包含5个字符,则在更改ItemsSource之后,每个项目的文本最多可显示5个字符(在新的ItemsSource中)。我该如何覆盖这个问题?
代码示例:
<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>
我使用的是BureauBlue主题,但无论如何,如果我不使用它,我也会遇到同样的问题。
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;
}
}
}
答案 0 :(得分:2)
GridView不会使用新数据重新计算宽度。要重置宽度,您可以使用以下
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;
}
}