【发布时间】:2013-02-20 06:52:00
【问题描述】:
在ListBox 中,我有一个ItemContainer 的IsSelected 属性使用<ListBox.ItemContainerStyle> 语法绑定到我的ViewModel 的IsSelected 属性。
它工作正常,但我收到了 Resharper 警告:
无法解析“FooSolution.BarViewModel”类型的数据上下文中的属性“IsSelected”。
如何在 ListBox ItemContainer 上指定 DataContext 类型以消除此警告?
这里是代码。我有一个BarViewModel 类:
public ObservableCollection<FooViewModel> FooItems { get;set; }
BarViewModel 分配给包含 ListBox 的 Control 中的 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>
更新
正如 HighCore 所建议的,我尝试使用 setter 设置 d:DataContext,但不幸的是,它无济于事,甚至破坏了构建:
<Setter Property="d:DataContext" Value="{d:DesignInstance yourxmlns:yourItemViewModelClass}"/>
(抛出:错误 1 标签“DesignInstance”在 XML 命名空间“schemas.microsoft.com/expression/blend/2008”中不存在;。第 31 行位置 50。)
更新 2
最后,解决方案是在样式元素本身上设置d:DataContext(请参阅下面的答案):
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance local:FooViewModel }">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
【问题讨论】:
标签: c# wpf silverlight xaml binding