对于给出的答案不满意,我试图自己找到一个解决方案......
结果更像是一种黑客方式而不是解决方案,但对我来说这很好用。这个解决方案以一种特殊的方式使用了MultiBindings。
首先它可能看起来像是一堆代码,但你可以用非常少的努力重复使用它。
首先我实现了一个“IMultiValueConverter”
public class SelectedItemsMerger : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
SelectedItemsContainer sic = values[1] as SelectedItemsContainer;
if (sic != null)
sic.SelectedItems = values[0];
return values[0];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return new[] { value };
}
}
还有一个SelectedItems容器/包装:
public class SelectedItemsContainer
{
public object SelectedItems { get; set; }
}
现在我们为我们的ListBox.SelectedItem(单数)创建绑定。注意:您必须为“转换器”创建静态资源。这可以在每个应用程序中完成一次,并可重复使用于所有需要转换器的ListBox。
<ListBox.SelectedItem>
<MultiBinding Converter="{StaticResource SelectedItemsMerger}">
<Binding Mode="OneWay" RelativeSource="{RelativeSource Self}" Path="SelectedItems"/>
<Binding Path="SelectionContainer"/>
</MultiBinding>
</ListBox.SelectedItem>
在ViewModel中,我创建了一个容器,可以进行绑定。重要的是要使用new()来初始化它,以便将其填充到值中。
SelectedItemsContainer selectionContainer = new SelectedItemsContainer();
public SelectedItemsContainer SelectionContainer
{
get { return this.selectionContainer; }
set
{
if (this.selectionContainer != value)
{
this.selectionContainer = value;
this.OnPropertyChanged("SelectionContainer");
}
}
}
就是这样。也许有人看到了一些改进的地方?你对此有什么想法吗?
RaisePropertyChangedEventHandler
的分派程序处,BindableCollection
构造函数会抛出一个InvalidOperationException
。我尝试在catch块中使用Dispatcher.BeginInvoke
放置一个try/catch块,但是当页面导航回来时,列表项不会重新选择。 - kck