我已经构建了自己的usercontrol模板,继承的类看起来像:
using System.Windows.Controls;
using CustomCopyNas.Views;
namespace CustomCopyNas.MVVM
{
/// <summary>
/// Base class for all Views that is used in MVVM
/// </summary>
/// <typeparam name="TViewModel">ViewModel</typeparam>
public class ViewBase<TViewModel> : UserControl, IView<TViewModel> where TViewModel : UploadViewModelBase
{
public ViewBase()
{ }
public ViewBase(TViewModel tViewModel)
{
ViewModel = tViewModel;
}
/// <summary>
/// ViewModel
/// </summary>
public TViewModel ViewModel
{
get
{
return (TViewModel)DataContext;
}
private set
{
DataContext = value;
}
}
}
}
我的xaml文件
<mvvm:ViewBase x:Class="CustomCopyNas.Controls.FolderControl"
x:TypeArguments="vm:FolderViewModel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mvvm="clr-namespace:CustomCopyNas.MVVM"
xmlns:vm="clr-namespace:CustomCopyNas.Views"
xmlns:enum="clr-namespace:CustomCopyNas.Enum"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" Width="700">
<mvvm:ViewBase.Resources>
<ObjectDataProvider x:Key="osEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="enum:OsType"></x:Type>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</mvvm:ViewBase.Resources>
<Grid>
<DataGrid ItemsSource="{Binding Folders, Mode=TwoWay}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Folder or File" Binding="{Binding Path}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</mvvm:ViewBase>
和部分类
using CustomCopyNas.MVVM;
using CustomCopyNas.Views;
namespace CustomCopyNas.Controls
{
/// <summary>
/// Interaction logic for FolderControl.xaml
/// </summary>
public partial class FolderControl : ViewBase<FolderViewModel>
{
public FolderControl()
: base(new FolderViewModel("SourceFolders.xml"))
{
InitializeComponent();
}
}
}
当我尝试编译时,我遇到错误,视图库上不存在属性资源。我没想到,错误在哪里,我的viewbase类继承自usercontrol类,这提供了资源属性。
这有什么不对?
答案 0 :(得分:2)
我认为您的问题是由XAML中不支持泛型类引起的。您可以在MSDN的Generics in XAML页面上阅读完整的故事,但简而言之,可以从链接页面阅读:
在XAML中,泛型类型必须始终表示为约束泛型; XAML类型系统或XAML节点流中不存在无约束泛型,并且不能在XAML标记中表示。
因此,您的代码类声明之间存在不匹配:
public class ViewBase<TViewModel>
您的XAML类声明:
<mvvm:ViewBase x:Class="CustomCopyNas.Controls.FolderControl"
它们不匹配会导致各种问题。
有关此主题的更多信息,请参阅Can I specify a generic type in XAML?和WPF UserControl with generic code-behind个问题。