根据标题,当基类是泛型时,如何在XAML中设置依赖属性?尝试这样做时,我会得到NullReferenceException,从代码后台设置属性可以正常工作。当基类不是泛型时,它也可以正常工作。
我正在使用.NET4
以下是一些示例代码:
WindowBase.cs
using System.Windows;
namespace GenericDependencyPropertyTest
{
public class WindowBase<ViewModel> : Window
{
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(
"Header", typeof(string), typeof(WindowBase<ViewModel>), new PropertyMetadata("No Header Name Assigned"));
public string Header
{
get { return (string)GetValue(HeaderProperty); }
protected set { SetValue(HeaderProperty, value); }
}
protected virtual ViewModel Model { get; set; }
}
}
MainWindow.xaml
<local:WindowBase x:Class="GenericDependencyPropertyTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GenericDependencyPropertyTest"
x:TypeArguments="local:IMyViewModel"
Title="MainWindow" Height="350" Width="525" Header="Test">
<Grid>
</Grid>
</local:WindowBase>
MainWindow.xaml.cs
namespace GenericDependencyPropertyTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : WindowBase<IMyViewModel>
{
public MainWindow()
{
InitializeComponent();
}
protected override IMyViewModel Model
{
get
{
return base.Model;
}
set
{
base.Model = value;
}
}
}
}
IMyViewModel.cs
namespace GenericDependencyPropertyTest
{
public interface IMyViewModel
{
}
}