通用参数约束违规?

时间:2019-11-04 08:49:16

标签: c# wpf xaml

我已经声明了一个基本的对话框窗口类,该类键入datacontext以确保附加的viewmodel具有适当的返回类型。当我尝试使用它时,尽管出现通用参数错误:

  

GenericArguments [1],   'Mocks.MidSoft_Hospitality_ViewModels_Dialogs_ReceiveItemViewModel_32_569724456',   上   'Mocks.MidSoft_Hospitality_Views_Dialogs_BaseDialogWindow`2_32_569724456 [TResult,TViewModel]'   违反了类型'TViewModel'的约束。

我不明白为什么会这样

基本对话框窗口声明:

public class BaseDialogWindow<TResult, TViewModel> : DialogWindowBase<TResult> where TViewModel: ViewModels.Dialogs.DialogBaseViewModel<TResult>
{
    public BaseDialogWindow() : base()
    {

    }

    new public TViewModel DataContext
    {
        get => this.GetValue(DataContextProperty) as TViewModel;
        set => this.SetValue(DataContextProperty, value);
    }

}

DialogWindowBase:

public class DialogWindowBase<TResult> : Window, IDialog<TResult>
{
    public DialogWindowBase()
    {
        //Formatting code here
    }

    public Result Result { get; set; } = Result.None;

    public TResult ReturnData { get; set; }

}

viewModel:

public class ReceiveItemViewModel : ViewModels.Dialogs.DialogBaseViewModel<ReceiveItemResult>
{
    //View Model Code here
}

和xaml:

<local:BaseDialogWindow x:Class="MidSoft.Hospitality.Views.Dialogs.ReceiveItemDialog"
                        x:TypeArguments="local:ReceiveItemResult, vm:ReceiveItemViewModel"
                        xmlns:vm="clr-namespace:MidSoft.Hospitality.ViewModels.Dialogs"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                        xmlns:local="clr-namespace:MidSoft.Hospitality.Views.Dialogs"
                        mc:Ignorable="d"
                        d:DataContext="{d:DesignInstance vm:ReceiveItemViewModel, IsDesignTimeCreatable=False}"
                        x:Name="ReceiveStockItemDialog"
                        Height="450" Width="800">
    <Grid>
    </Grid>
</local:BaseDialogWindow>

对话框代码:

    public partial class ReceiveItemDialog
    {
        public ReceiveItemDialog()
        {
            InitializeComponent();
        }
    }

我上面引用的错误是我得到的唯一编译器错误。我将不胜感激对此错误的了解。

更新:我现在注意到应用程序正在编译并运行,没有引发任何异常,但是错误仍然存​​在,并且xaml设计器将其显示为无效标记

1 个答案:

答案 0 :(得分:1)

IsDesignTimeCreatable=False将迫使设计人员忽略指定的DesignInstance类型,并使用反射创建替代类型。在这种情况下,设计人员无法识别通用类型,因为它是复杂类型而不是原始类型,因此无法使用适当的通用参数TViewModel创建适当的模拟实例。

要解决此问题,可以将IsDesignTimeCreatable属性设置为True并在ReceiveItemViewModel上实现默认构造函数。如果无法使用默认构造函数,则仅在设计时DesignInstance引入包装类型,然后将其用作默认构造函数即可正确初始化基本类型ReceiveItemViewModel