【发布时间】:2021-02-03 08:54:31
【问题描述】:
我想在DataGrid 上保存/加载列订单。我正在尝试在我的 ViewModel 和 View 之间绑定一个包含 DataGrid 列索引的 StringCollection。我可以在我的 ViewModel 中成功设置StringCollection,它使用附加属性更新视图,但是当我使用 UI 更改视图中的列顺序时,ViewModel 不会更新以反映新的列顺序。如何让我的 ViewModel 监听 View 的变化?
我的 xaml
<DataGrid ItemsSource="{Binding MyObservableCollection}"
attach:DataGridColumnChanger.ColumnOrder="{Binding ColumnOrders, Mode=TwoWay}">
</DataGrid>
我的附属财产
public class DataGridColumnChanger : DependencyObject
{
#region dependency properties
public static StringCollection GetColumnOrder(DependencyObject obj)
{
return (StringCollection)obj.GetValue(ColumnOrderProperty);
}
public static void SetColumnOrder(DependencyObject obj, StringCollection value)
{
obj.SetValue(ColumnOrderProperty, value);
}
public static readonly DependencyProperty ColumnOrderProperty = DependencyProperty.RegisterAttached("ColumnOrder",
typeof(StringCollection), typeof(DataGridColumnChanger), new UIPropertyMetadata(new StringCollection(), new PropertyChangedCallback(OnColumnOrderChange)));
#endregion
private static void OnColumnOrderChange(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var element = obj as DataGrid;
if (element != null)
{
try
{
StringCollection collection = (StringCollection)e.NewValue;
if (collection != null && collection.Count > 0)
{
for (int j = 0; j <= element.Columns.Count - 1; j++)
{
int index = Convert.ToInt32(collection[j]);
element.Columns[j].DisplayIndex = index;
}
}
}
catch
{
Console.WriteLine("Error");
}
}
}
}
我的视图模型
private StringCollection columnOrders = new StringCollection();
public System.Collections.Specialized.StringCollection ColumnOrders
{
get => this.columnOrders;
set
{
this.columnOrders = value;
this.RaisePropertyChanged("ColumnOrders");
}
}
【问题讨论】:
-
您应该在附加的属性代码中订阅您的
DataGrid更改并相应地调用SetColumnOrder。您的绑定怎么会知道您从未更改附加属性的值? -
看起来怎么样?您的意思是在附加的属性类中监听诸如 ColumnDisplayIndexChanged 之类的事件并在其中调用 SetColumnOrder 吗?
-
是的,应该就是这样
-
@chris 在这种情况下你想做什么,更新现有的集合还是每次都创建一个新的集合?另一个问题是,如何初始化集合,代码仅在字符串集合为空或具有 for all 列的项目时才有效。说到集合,为什么显示索引是
int时使用StringCollection?
标签: c# wpf xaml data-binding