WPF でリストビュー コントロールを作成し、完全にバインドされたIcollectionview
オブジェクトを取得しましたObservableCollection<object>
。私のリストビュー列は動的に作成されます。リストビューを並べ替えてグループ化する必要がありますが、正しく機能していません。私のコードは以下の通りです。
private void LaodList()
{
dt = new DataTable();
dt.Columns.Add("AA", typeof(string));
dt.Columns.Add("BB", typeof(string));
dt.Columns.Add("cc", typeof(string));
dt.Rows.Add("12", "66",11);
dt.Rows.Add("33", "44",22);
dt.AcceptChanges();
GridView gv = new GridView();
//gv.AllowsColumnReorder = true;
List<string> myItemsCollection = new List<string>();
for (int i = 0; i < dt.Columns.Count; i++)
{
GridViewColumn col = new GridViewColumn();
col.Header = dt.Columns[i].ColumnName;
col.DisplayMemberBinding = new Binding(string.Format("[{0}]", i));
gv.Columns.Add(col);
myItemsCollection.Add(col.Header.ToString());
}
LvItems.View = gv;
this.Source = CollectionViewSource.GetDefaultView(LoadItems(dt)) ;
LvItems.DataContext = this.Source;
cmbGroups.ItemsSource = myItemsCollection;
}
public ObservableCollection<object> LoadItems(DataTable dt)
{
ObservableCollection<object> items = new ObservableCollection<object>();
foreach (DataRow dataRow in dt.Rows)
{
items.Add(dataRow.ItemArray);
}
return items;
}
//sort////////////////////////
private void ListView_Click(object sender, RoutedEventArgs e)
{
GridViewColumnHeader currentHeader = e.OriginalSource as GridViewColumnHeader;
if (currentHeader != null && currentHeader.Role != GridViewColumnHeaderRole.Padding)
{
if (this.Source.SortDescriptions.Count((item) => item.PropertyName.Equals(currentHeader.Column.Header.ToString())) > 0)
{
SortDescription currentPropertySort = this.Source
.SortDescriptions
.First<SortDescription>(item => item.PropertyName.Equals(currentHeader.Column.Header.ToString()));
//Toggle sort direction.
ListSortDirection direction =
(currentPropertySort.Direction == ListSortDirection.Ascending) ?
ListSortDirection.Descending : ListSortDirection.Ascending;
//Remove existing sort
this.Source.SortDescriptions.Remove(currentPropertySort);
this.Source.SortDescriptions.Insert(0, new SortDescription(currentHeader.Column.Header.ToString(), direction));
}
else
{
this.Source.SortDescriptions.Insert(0, new SortDescription(currentHeader.Column.Header.ToString(), ListSortDirection.Ascending));
}
this.Source.Refresh();
}
}
//group////////////////////
private void btnGroup_Click(object sender, RoutedEventArgs e)
{
this.Source.GroupDescriptions.Clear();
PropertyInfo pinfo = typeof(object).GetProperty(cmbGroups.Text);
if (pinfo != null)
this.Source.GroupDescriptions.Add(new PropertyGroupDescription(pinfo.Name));
}
WPFコードは以下の通りです
<ListView ItemsSource="{Binding}" x:Name="LvItems" ButtonBase.Click="ListView_Click" IsSynchronizedWithCurrentItem="True" Grid.Row="1" Margin="0,22,0,43">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontSize="15" FontWeight="Bold" Text="{Binding}"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>