我正在尝试在listview中获取gridviewcolumns,以便在更新Binding源时自动调整内容大小(viewmodel上的observablecollection)。
listview填充正常,但在刷新/更新集合时无法正常工作。这是我到目前为止所尝试的解决方案:
XAML:
<ListView x:Name="ListView" ItemsSource="{Binding Collection, NotifyOnSourceUpdated=True}" SourceUpdated="ListView_SourceUpdated">
<ListView.View>
<GridView>
<GridViewColumn Width="Auto" Header="Test" DisplayMemberBinding={Binding Test}" />
</GridView>
</ListView.View>
</ListView>
Codebehind:
private void requestsListView_SourceUpdated(object sender, DataTransferEventArgs e)
{
GridView gv = requestsListView.View as GridView;
if (gv != null)
{
foreach (var c in gv.Columns)
{
if (double.IsNaN(c.Width))
{
c.Width = c.ActualWidth;
}
c.Width = double.NaN;
}
}
}
据我所知,SourceUpdated事件永远不会触发。我不知道这是因为datacontext设置为ViewModel?不确定如何从VM与ListView进行交互。
有没有更好的方法尝试使用ViewModel执行此操作?还是新手,并试图学习MVVM。
答案 0 :(得分:1)
这是一个有效的例子:
<Window x:Class="ListViewAutoResize.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ListView x:Name="lv" Background="Beige" ItemsSource="{Binding items}" >
<ListView.View>
<GridView>
<GridViewColumn Header="Column1" DisplayMemberBinding="{Binding}"/>
<GridViewColumn Header="Column2" DisplayMemberBinding="{Binding}"/>
<GridViewColumn Header="Column3" DisplayMemberBinding="{Binding}"/>
</GridView>
</ListView.View>
</ListView>
<Button Content="Add item" Click="btnAddItem_OnClick"/>
</StackPanel>
</Window>
以下是代码隐藏:
public partial class MainWindow : Window
{
public ObservableCollection<string> items { get; set; }
public MainWindow()
{
InitializeComponent();
items = new ObservableCollection<string>();
items.Add(("item1"));
items.Add(("item2"));
items.Add(("item3333"));
items.Add(("item4"));
items.Add(("item5"));
items.CollectionChanged += items_CollectionChanged;
this.DataContext = this;
}
void items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
var view = lv.View as GridView;
AutoResizeGridViewColumns(view);
}
static void AutoResizeGridViewColumns(GridView view)
{
if (view == null || view.Columns.Count < 1) return;
// Simulates column auto sizing
foreach (var column in view.Columns)
{
// Forcing change
if (double.IsNaN(column.Width))
column.Width = 1;
column.Width = double.NaN;
}
}
private void btnAddItem_OnClick(object sender, RoutedEventArgs e)
{
items.Add("aaaaaaaaaabbbbbbb");
}
}
就是这样。
在:
后:
答案 1 :(得分:0)
SourceUpdated事件永远不会触发,因为您从未更改属性值集合或属性集合未通知。您可以通过Binding在xaml中设置一次,但集合中内容的更改不会触发事件SourceUpdate。
您正确使用实现接口 INotifyCollectionChanged 的ObservableCollection。因此,您可以在该集合上挂钩事件 CollectionChanged 。