【问题标题】:Specifying design-time type for items of non-generic collection为非泛型集合项指定设计时类型
【发布时间】:2018-03-19 15:33:55
【问题描述】:

我正在尝试指定所有 .xaml 文件的设计时 DataContext,以便最大限度地利用 Resharper 及其重构和警告不存在绑定的能力。我在处理非泛型集合时遇到了问题。

在这篇文章中请记住,一切都在运行时完美运行,这纯粹是一个设计时问题。

考虑以下 sn-ps:

MyList.cs

public class MyList : IList { ... }

MyClass.cs

public class MyClass {
    public string Name { get; set; }
    public string Description { get; set; }
}

MyViewModel.cs

public class MyViewModel {
    public MyList ItemsToDisplay { get; set; } // filled with items of type MyClass
}

MyWindow.xaml

<Window x:Class="MyWindow"
        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:telerik="http://schemas.telerik.com/2008/xaml/presentation"
        xmlns:my="clr-namespace:MyNameSpace"
        mc:Ignorable="d" d:DataContext="{d:DesignInstance my:MyViewModel}">

    <telerik:RadGridView ItemsSource="{Binding ItemsToDisplay}">
        <telerik:RadGridView.Columns>
            <telerik:GridViewDataColumn DataMemberBinding="{Binding Name}" Header="Name"/>
            <telerik:GridViewDataColumn DataMemberBinding="{Binding Description}" Header="Description"/>
        </telerik:RadGridView.Columns>
    </telerik:RadGridView>

</Window>

此设置的问题是我在列的绑定上收到以下警告:Cannot resolve property 'Name' in context of type 'object'.

如果我将MyViewModel.cs 更改为具有IList&lt;MyClass&gt; ItemsToDisplay 属性,Resharper 将成功识别该集合具有MyClass 类型的项目并正确解析数据上下文,从而消除警告。但是,由于代码限制,我无法更改集合的类型。

所以我的问题是:是否有一些隐藏的 xaml 魔法可以让我做这样的事情并指定集合的​​类型?伪代码:

<telerik:RadGridView ItemsSource="{Binding ItemsToDisplay, d:ItemsSourceType=my:MyClass}">

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    我建议您查看TypeDescriptor 并为您的项目类型创建一个自定义类型描述符。不确定这是否适用于您的具体情况,但至少可以尝试一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多