2014-09-10 68 views
1

这是我创建的一个小例子,用于说明我的问题。Visual Studio无法识别WPF中数据绑定的正确类型

public class DataItem 
{ 
    public DataItem() {} 
    public DataItem(bool isSelected) 
    { 
     IsSelected = isSelected; 
    } 

    public bool IsSelected { get; set; } 
} 


public class MainViewModel : ViewModelBase 
{ 
    public MainViewModel() 
    { 
     Items = new ObservableCollection<DataItem> {new DataItem(true), new DataItem()}; 
    } 

    public ObservableCollection<DataItem> Items { get; set; } 
} 

的XAML是:

<Window x:Class="RoomDesigner.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:ignore="http://www.ignore.com" 
     xmlns:viewModel="clr-namespace:RoomDesigner.ViewModel" 
     mc:Ignorable="d ignore" 
     Height="350" 
     Width="525" 
     d:DataContext="{d:DesignInstance viewModel:MainViewModel}"> 

    <Grid x:Name="LayoutRoot"> 
     <ListBox HorizontalAlignment="Left" Height="299" Margin="230,10,0,0" VerticalAlignment="Top" Width="100" 
       SelectionMode="Multiple" 
       ItemsSource="{Binding Items}"> 
      <ListBox.ItemContainerStyle> 
       <Style TargetType="{x:Type ListBoxItem}"> 
        <Setter Property="IsSelected" Value="{Binding IsSelected}"/> <!--This line--> 
       </Style> 
      </ListBox.ItemContainerStyle> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding IsSelected}"></TextBlock> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

    </Grid> 
</Window> 

此示例按预期工作:选择项目总是有True写在上面,并False写在未选中的项目。

但是,Visual Studio(或Resharper)在标记的行上强调了单词IsSelected,并且建议表示Cannot resolve property 'IsSelected' in data context of type 'RoomDesigner.ViewModel.MainViewModel'。它想要绑定到MainViewModel而不是DataItem这就是为什么。

我使用Visual Studio 13 SP3和Resharper 8.1。

我想知道这个奇怪的行为来自哪里,如果有办法解决它,因为它有点烦人。

回答