【问题标题】:Can a DataTemplate be tied to a nested class?DataTemplate 可以绑定到嵌套类吗?
【发布时间】:2012-09-30 03:54:02
【问题描述】:

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 部分中是如何完成的?

提前谢谢... 乔

【问题讨论】:

    标签: wpf xaml mvvm datatemplate nested-class


    【解决方案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 标记扩展中的. 更改为+

    感谢:this thread

    【讨论】:

    • 工作就像一个魅力,虽然我立即遇到了 VS2010 问题,WPF 设计器在使用它时无法显示表单。但是,绑定确实工作正常。
    • 到底有没有人会想出这个语法?应该有一项法律禁止微软设计和实施 API。
    • @ATL_DEV:强烈同意!
    猜你喜欢
    • 2022-01-20
    • 2014-03-12
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多