【问题标题】:Visual studio does not recognize the correct type for data binding in WPFVisual Studio 无法识别 WPF 中数据绑定的正确类型
【发布时间】:2014-11-04 06:49:48
【问题描述】:

这是我创建的一个小例子来说明我的问题。

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。

我想知道这种奇怪的行为是从哪里来的,是否有办法解决它,因为它有点烦人。

【问题讨论】:

    标签: c# wpf xaml visual-studio-2013 resharper


    【解决方案1】:

    您应该在 Style 元素上设置 d:DataContext。 ItemContainerStyle 属性不会自动推断。

    <Style TargetType="{x:Type ListBoxItem}" d:DataContext="{d:DesignInstance viewModel:DataItem}">
        <Setter Property="IsSelected" Value="{Binding IsSelected}"/>  <!--This line-->
    </Style>
    

    查看类似问题:Specify datacontext type on listbox ItemContainer in style
    另一个类似的问题:How does this setter end up working? (ListView MultiSelect)

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 1970-01-01
      • 2022-07-15
      • 2023-03-23
      • 1970-01-01
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多