如何扩展 xaml 个对象?
How to extend xaml objects?
如果我扩展现有对象,例如 DataGrid
:
public class CustomDataGrid : DataGrid
{
static CustomDataGrid()
{
CommandManager.RegisterClassCommandBinding(
typeof(CustomDataGrid),
new CommandBinding(ApplicationCommands.Paste,
new ExecutedRoutedEventHandler(OnExecutedPaste),
new CanExecuteRoutedEventHandler(OnCanExecutePaste)));
}
...
在 xaml 方面,如果我尝试使用 <CustomDataGrid/>
,我会得到类似 CustomDataGrid is not supported in a Windows Presentation Foundation (WPF) project
的结果。那么我如何在 xaml 端实际使用扩展的 class 呢?
您需要通过命名空间引用 class。这涉及将名称空间声明添加到 Xaml 文件的顶部,然后在控件元素中使用该名称空间。
如果我们假设您的 CustomDataGrid
位于名为 Rhubarb
的名称空间中,与您正在编写的 Xaml 在同一程序集中,您需要添加此属性到 Xaml 文件中的根标签(与其他 xmlns
属性一起):
xmlns:rhubarb="clr-namespace:Rhubarb"
然后,在您声明网格的地方,改用此元素:
<rhubarb:CustomDataGrid />
如果您的 cod 在一个单独的(引用的)程序集中,您需要这样修改命名空间声明:
xmlns:rhubarb="clr-namespace:Rhubarb;assembly=NameOfYourAssembly"
(请注意程序集名称上没有 .dll
后缀。)
如果我扩展现有对象,例如 DataGrid
:
public class CustomDataGrid : DataGrid
{
static CustomDataGrid()
{
CommandManager.RegisterClassCommandBinding(
typeof(CustomDataGrid),
new CommandBinding(ApplicationCommands.Paste,
new ExecutedRoutedEventHandler(OnExecutedPaste),
new CanExecuteRoutedEventHandler(OnCanExecutePaste)));
}
...
在 xaml 方面,如果我尝试使用 <CustomDataGrid/>
,我会得到类似 CustomDataGrid is not supported in a Windows Presentation Foundation (WPF) project
的结果。那么我如何在 xaml 端实际使用扩展的 class 呢?
您需要通过命名空间引用 class。这涉及将名称空间声明添加到 Xaml 文件的顶部,然后在控件元素中使用该名称空间。
如果我们假设您的 CustomDataGrid
位于名为 Rhubarb
的名称空间中,与您正在编写的 Xaml 在同一程序集中,您需要添加此属性到 Xaml 文件中的根标签(与其他 xmlns
属性一起):
xmlns:rhubarb="clr-namespace:Rhubarb"
然后,在您声明网格的地方,改用此元素:
<rhubarb:CustomDataGrid />
如果您的 cod 在一个单独的(引用的)程序集中,您需要这样修改命名空间声明:
xmlns:rhubarb="clr-namespace:Rhubarb;assembly=NameOfYourAssembly"
(请注意程序集名称上没有 .dll
后缀。)