可一个DataTemplate绑定到一个嵌套类?(Can a DataTemplate be tie

2019-09-23 20:40发布

在XAML一个DataTemplate与嵌套类关联?

我工作的一个MVVM应用程序,我遇到了一个数据模板的问题。 我有提供其它视图模型的集合项控件视图模型。 这些项目是定义为外视图模型嵌套类层次结构的一部分。 我一直无法到目前为止XAML创建一个映射,以引用内部嵌套类。

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

public class MainViewModel
{
    public class A
    {
    }

    public class B : A
    {
    }

    public class C : A
    {
    }

    public ObservableCollection<A> Items
    {
        get;
        set;
    }
}

在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>

问题是:到嵌套类的引用显示为在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...

如果我移动A,B,C类层次的MainViewModel类(即命名空间级别)之外,这工作正常。

作为一般的习惯,我尽量保持相关被定义为在其内嵌套类视图模型类,但是这使我这个问题。

所以,我的问题:是它甚至有可能到一个DataTemplate与嵌套类关联? 如果是这样,如何在XAML中部分做了什么?

在此先感谢乔...

Answer 1:

这对我的作品:

 <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>

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

信用: 此线程



文章来源: Can a DataTemplate be tied to a nested class?