我的应用正在使用 avalondock 和 prims 并且遇到了确切的问题。我对 BSG 有同样的想法,当我们在 MVVM 应用程序中切换选项卡或文档内容时,列表视图 + 框、组合框等控件已从 VisualTree 中删除。我窃听并看到它们中的大多数数据都被重置为 null,例如 itemssource、selecteditem、.. 但 selectedboxitem 仍然保持当前值。
模型中有一个方法,检查它的值为 null 然后返回如下:
private Employee _selectedEmployee;
public Employee SelectedEmployee
{
get { return _selectedEmployee; }
set
{
if (_selectedEmployee == value ||
IsAdding ||
(value == null && Employees.Count > 0))
{
return;
}
_selectedEmployee = value;
OnPropertyChanged(() => SelectedEmployee);
}
但是这种方法只能在第一个绑定级别上解决得很好。我是说,
如果想将 SelectedEmployee.Office 绑定到组合框,我们该怎么做,这样做不好
如果签入 SelectedEmployee 模型的 propertyChanged 事件。
基本上,我们不希望它的值被重置为空,保持它的预值。我找到了一个新的解决方案
始终如一。通过使用附加属性,我为 Selector 控件创建了 KeepSelection a-Pro,bool 类型,从而将其继承的所有内容提供为 listview、combobox...
public class SelectorBehavior
{
public static bool GetKeepSelection(DependencyObject obj)
{
return (bool)obj.GetValue(KeepSelectionProperty);
}
public static void SetKeepSelection(DependencyObject obj, bool value)
{
obj.SetValue(KeepSelectionProperty, value);
}
// Using a DependencyProperty as the backing store for KeepSelection. This enables animation, styling, binding, etc...
public static readonly DependencyProperty KeepSelectionProperty =
DependencyProperty.RegisterAttached("KeepSelection", typeof(bool), typeof(SelectorBehavior),
new UIPropertyMetadata(false, new PropertyChangedCallback(onKeepSelectionChanged)));
static void onKeepSelectionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var selector = d as Selector;
var value = (bool)e.NewValue;
if (value)
{
selector.SelectionChanged += selector_SelectionChanged;
}
else
{
selector.SelectionChanged -= selector_SelectionChanged;
}
}
static void selector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selector = sender as Selector;
if (e.RemovedItems.Count > 0)
{
var deselectedItem = e.RemovedItems[0];
if (selector.SelectedItem == null)
{
selector.SelectedItem = deselectedItem;
e.Handled = true;
}
}
}
}
最后,我只是在 xaml 中使用这种方法:
<ComboBox lsControl:SelectorBehavior.KeepSelection="true"
ItemsSource="{Binding Offices}"
SelectedItem="{Binding SelectedEmployee.Office}"
SelectedValuePath="Id"
DisplayMemberPath="Name"></ComboBox>
但是,如果选择器的 itemssource 有项目,则 selecteditem 永远不会为空。它可能会影响
一些特殊的上下文。
希望对您有所帮助。
祝你好运! :D
龙山