我有一个ObservableCollection绑定(bind)到tabcontrol
。
<TabControl
ItemsSource="{Binding Steps}"
SelectedItem="{Binding SelectedStep}"
CanUserReorder="{Binding EditMode}"
</TabControl>
如果用户处于EditMode,则可以重新排序选项卡项。
当我离开带有tab控件的 View 时,我失去了由用户修改的Tab键顺序。
我该如何预防?
谢谢你的帮助!
最佳答案
我得到了它!
该解决方案在mvvm-pattern中实现。
每次更改收集步骤时,请添加或删除项目,然后重新排列其位置。
用户可以通过使用ComponentOne的TabControl或使用Bea Stollnitz的拖放功能来重新排序View中TabControl的TabItem。
ViewModel:
public class MyViewModel
{
public MyModel Model {/*get... set*/}
public ObservableCollection<StepViewModel> Steps {/*get... set...*/}
public StepViewModel SelectedStep {/*get... set...*/}
public MyViewModel()
{
Model = new MyModel();
Steps = new ObservableCollection<StepViewModel>();
Model.Steps = new ObservableCollection<StepModel>();
// Load the saved Model with the steps and their positions
Model.Steps = LoadFromXml();
Steps.CollectionChanged += Steps_OnCollectionChanged;
// Add the Steps in the right order
for (int i = 0; i < Steps.Count; i++)
{
var item = Steps.First(x => x.Position == i);
var vm = new StepViewModel();
Steps.Add(vm);
}
}
private void Steps_OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (StepViewModel vm in e.NewItems)
{
if (!Model.Steps.Contains(vm.Model))
Model.Steps.Add(vm.Model);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (StepViewModel vm in e.OldItems)
{
if (Model.Steps.Contains(vm.Model))
Model.Steps.Remove(vm.Model);
}
}
// Match the temporary collectionindex to a position-property
foreach (StepViewModel item in Steps)
{
item.Position = Steps.IndexOf(item);
}
}
}