【发布时间】:2010-09-02 17:03:53
【问题描述】:
正如标题所说,当基类是泛型时,如何在 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
{
}
}
【问题讨论】:
-
“当基类是泛型时”是什么意思?你是想说自定义控件吗?
-
抱歉不清楚。我的意思是从通用类继承的控件(或本例中的窗口),在上面的示例中,我传递了一个接口,用于窗口将具有的视图模型类型,因为 MainWindow 继承自 WindowBase。
标签: c# wpf generics xaml .net-4.0