如何为样式指定设计器datacontext,以便Resharper找到我的属性?

JCH*_*H2k 20 c# wpf resharper xaml mvvm

我经常将TreeViewItem的IsExpanded和IsSelected属性绑定到我的viewmodel.例如,这使得可以在加载树时使项目预扩展,或者在选择树时扩展项目.

XAML看起来像这样:

<Window x:Class="StyleSetterDatatypeTest.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
            xmlns:test="clr-namespace:StyleSetterDatatypeTest"
            Title="MainWindow" Height="350" Width="525"
            mc:Ignorable="d"
            d:DataContext="{d:DesignInstance test:TestViewModel, IsDesignTimeCreatable=True}">

    <TreeView ItemsSource="{Binding Items}">
        <TreeView.Resources>
            <Style TargetType="TreeViewItem">
                <Setter Property="IsExpanded" Value="{Binding ItemExpanded}"/>
                <Setter Property="IsSelected" Value="{Binding ItemSelected}"/>
            </Style>

            <HierarchicalDataTemplate DataType="{x:Type test:TestItemViewModel}" ItemsSource="{Binding Children}">
                <TextBlock Text="{Binding Name}"/>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
</Window>
Run Code Online (Sandbox Code Playgroud)

我的viewmodel看起来像这样:

public class TestItemViewModel
{
    public bool ItemExpanded { get; set; }

    public bool ItemSelected { get; set; }

    public string Name { get; set; }

    public string[] Children
    {
        get { return new [] {"Child 1", "Child 2"}; }
    }
}
Run Code Online (Sandbox Code Playgroud)

这在执行和设计器中工作正常,但Resharper在Bindings中找不到ItemSelected和ItemExpanded属性,并将它们作为警告加下划线.
我可以理解为什么它找不到它们(我从未指定"TestViewModel"作为Style的Datacontext类型),但我该如何解决这个问题呢?没有Style-Design-Datacontext这样的东西......

更新:

这里的问题是,样式在TreeView中定义,并且DataContext显然设置为TestViewModel.检查器没有得到,我的样式是TreeView 项,并且此项具有Test Item ViewModel(ItemsSource元素的类型)的DataContext .

哦,我也尝试在TreeView.ItemContainerStyle中设置样式,如果TreeView.Resources(这里应该清楚DataContext必须是TextItemViewModel),但这不会改变任何东西......

N. *_*sev 48

@ lhildebrandt的答案通常是正确的,但在我的情况下,此解决方案会产生错误,完全禁止在设计器中显示视图.指定<d:Style.DataContext> 内部 <Style>标记帮助了我.

<Style>
    <d:Style.DataContext>
        <x:Type Type="local:MyTreeItem" />
    </d:Style.DataContext>
    <!--usual setters, triggers, etc.-->
</Style>
Run Code Online (Sandbox Code Playgroud)

这样d:DataContext也可以为控件指定,我们可以提供接口,嵌套类甚至泛型,没有任何错误:https: //stackoverflow.com/a/46637478/5598194

  • 为什么在使用“&lt;Style d:DataContext=local:MyTreeItem...”时它不起作用,但在执行“&lt;d:Style.DataContext&gt;...”时却起作用? (5认同)
  • 它工作了一段时间,但现在(VS 16.7.2),我收到以下错误:命名空间“http://schemas.microsoft.com/expression/blend/2008”中不存在名称“Style”。并且设计器仅显示“无效标记”消息。 (3认同)
  • 对此有任何麻烦的人:这就是命名空间应为xmlns:mc =“ http://schemas.openxmlformats.org/markup-compatibility/2006”的方式。xmlns:d =“ http://schemas.microsoft。 com / expression / blend / 2008“``mc:Ignorable =” d“` (2认同)