DataTemplate可以绑定到嵌套类吗?

Joe*_*e K 8 wpf xaml datatemplate mvvm nested-class

XAML中的DataTemplate可以与嵌套类相关联吗?

我正在研究MVVM应用程序,我遇到了数据模板问题.我有一个视图模型,为项目控件提供其他视图模型的集合.这些项是在外部视图模型中定义为嵌套类的层次结构的一部分.到目前为止,我还无法在XAML中创建一个映射来引用内部嵌套类.

这是类层次结构(为简洁起见而简化):

public class MainViewModel
{
    public class A
    {
    }

    public class B : A
    {
    }

    public class C : A
    {
    }

    public ObservableCollection<A> Items
    {
        get;
        set;
    }
}
Run Code Online (Sandbox Code Playgroud)

在XAML中,我正在尝试将DataTemplate映射到类型B和C,但我无法完全限定嵌套类名.

<ItemsControl ItemsSource="{Binding Path=Items}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type ns:BracingViewModel.B}">
            <Grid>
            ....
            </Grid>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ns:BracingViewModel.C}">
            <Grid>
            ....
            </Grid>
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>
Run Code Online (Sandbox Code Playgroud)

问题:对嵌套类的引用在XAML中显示为构建错误.我得到以下内容:

Error   5   Cannot find the type 'ns:B'. Note that type names are case sensitive. Line...

Error   5   Cannot find the type 'ns:C'. Note that type names are case sensitive. Line...
Run Code Online (Sandbox Code Playgroud)

如果我将A,B,C类层次结构移动到MainViewModel类之外(即命名空间级别),这样可以正常工作.

作为一般习惯,我尝试将与视图模型相关的类保持为定义为嵌套类,但这引出了我的问题.

所以,我的问题是:甚至可以将DataTemplate与嵌套类相关联吗?如果是这样,那么在XAML部分中如何完成?

提前谢谢......乔

小智 26

这对我有用:

 <ItemsControl ItemsSource="{Binding Path=Items}">
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type ns:MainViewModel+B}">
                <Grid Background="Blue"
                      Width="30"
                      Height="30">

                </Grid>
            </DataTemplate>
            <DataTemplate DataType="{x:Type ns:MainViewModel+C}">
                <Grid Background="Chartreuse" Width="30" Height="30">

                </Grid>
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>
Run Code Online (Sandbox Code Playgroud)

换句话说,只是改变.+x:Type标记扩展

信用:这个线程

  • 希望有人在神的世界上弄清楚这种语法吗?应该有一项法律禁止Microsoft设计和实现API。 (3认同)
  • 工作起来就像一个魅力,尽管我立即遇到了 VS2010 问题,WPF 设计器在使用时无法显示表单。但是,绑定确实工作得很好。 (2认同)