在ListBox中,我有一个ItemContainer的IsSelected属性使用< ListBox.ItemContainerStyle>绑定到我的viewmodel的IsSelected属性.句法.
它工作正常,但我得到一个Resharper警告:
Cannot resolve property ‘IsSelected’ in data context of type “FooSolution.Barviewmodel”.
如何在ListBox ItemContainer上指定指定DataContext类型以摆脱此警告?
public ObservableCollection<Fooviewmodel> FooItems { get;set; }
Barviewmodel被分配给包含ListBox的控件中的DataContext
和Fooviewmodel如下:
public bool IsSelected { get { return isSelected; } set { if (isSelected == value) { return; } isSelected = value; RaisePropertyChanged(() => IsSelected); } }
和XAML这样:
<ListBox ItemsSource="{Binding FooItems}" SelectionMode="Multiple"> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="IsSelected" Value="{Binding IsSelected}" /> </Style> </ListBox.ItemContainerStyle> </ListBox>
更新
我已经尝试使用设置器设置d:DataContext,如HighCore所建议的,但不幸的是,它不会帮助甚至打破构建:
<Setter Property="d:DataContext" Value="{d:DesignInstance yourxmlns:yourItemviewmodelClass}"/>
(抛出:错误1标签“DesignInstance”不存在于XML命名空间“schemas.microsoft.com/expression/blend/2008”;第31行位置50.)
更新2
Finaly,解决方案是在样式元素本身设置d:DataContext(请参见我的答案):
<ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance local:Fooviewmodel }"> <Setter Property="IsSelected" Value="{Binding IsSelected}" /> </Style>
解决方法
正如@HighCore所指出的那样,解决方案是从混合SDK中指定d:DataContext属性,但是只有在Style元素本身而不是属性setter中设置时,它才起作用:
<ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance local:Fooviewmodel }"> <Setter Property="IsSelected" Value="{Binding IsSelected}" /> </Style> </ListBox.ItemContainerStyle>