一个DataTemplate能否与一个嵌套类相绑定?

16

在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部分该如何做呢?
提前感谢... Joe
1个回答

43

这对我有效:

 <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 标记扩展中,只需将 . 改为 +

感谢:这个帖子的作者


2
运行得非常好,尽管我立即遇到了使用WPF设计器时无法显示表单的VS2010问题。但是,绑定功能运行良好。 - Joe K
8
任何人都该如何在这个世界上弄清楚这种语法?应该制定法律禁止微软设计和实施API。 - ATL_DEV
@ATL_DEV:非常同意! - Revious
太好了。它也适用于Xamarin.Forms。 - Junaid Pathan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接