加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在列表框中指定ItemContainer的datacontext类型

发布时间:2020-12-15 03:44:55 所属栏目:百科 来源:网络整理
导读:在ListBox中,我有一个ItemContainer的IsSelected属性使用 ListBox.ItemContainerStyle绑定到我的ViewModel的IsSelected属性.句法. 它工作正常,但我得到一个Resharper警告: Cannot resolve property ‘IsSelected’ in data context of type “FooSolution.B
在ListBox中,我有一个ItemContainer的IsSelected属性使用< ListBox.ItemContainerStyle>绑定到我的ViewModel的IsSelected属性.句法.

它工作正常,但我得到一个Resharper警告:

Cannot resolve property ‘IsSelected’ in data context of type “FooSolution.BarViewModel”.

如何在ListBox ItemContainer上指定指定DataContext类型以摆脱此警告?

这是代码.我有一个BarViewModel类:

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>

这将删除Resharper的警告,并且还会在ViewModel上重命名属性时更改绑定路径.凉!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读