Bob*_*Bob 13 .net c# generics wpf xaml
我有这个代码:
CustomUserControl.xaml.cs
namespace MyProject
{
public partial class CustomUserControl<T> : UserControl
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
而这个xaml:
CustomUserControl.xaml
<UserControl x:Class="MyProject.CustomUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid>
</Grid>
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为x:Class ="MyProject.CustomUserControl"与代码隐藏的泛型类定义不匹配.有没有办法使这项工作?
Lu5*_*u55 12
您可以在没有XAML文件的情况下创建通用的"代码隐藏"文件:
public class CustomUserControl<T>: UserControl
{ }
Run Code Online (Sandbox Code Playgroud)
而不是从它提供特定的类作为参数:
public partial class SpecificUserControl : CustomUserControl<Presenter>
{
public SpecificUserControl()
{
InitializeComponent();
}
}
Run Code Online (Sandbox Code Playgroud)
XAML:
<application:CustomUserControl
x:TypeArguments="application:Presenter"
xmlns:application="clr-namespace:YourApplicationNamespace"
...
Run Code Online (Sandbox Code Playgroud)
不幸的是,在Visual Studio 2012 Update 2之前,Visual Studio设计器似乎不支持此类泛型(请参阅/sf/answers/1057708081/)
到目前为止,在其他任何地方都找不到我的解决方案。主要区别在于,对于通用用户控件类,我只有一个.xaml文件,而对于每个实际用户控件却没有一个。
GenericUserControl.xaml.cs
using System.Windows.Controls;
namespace TestGenericUserControl
{
public abstract partial class GenericUserControl : UserControl
{
// If you use event handlers in GenericUserControl.xaml, you have to define
// them here as abstract and implement them in the generic class below, e.g.:
// abstract protected void MouseClick(object sender, MouseButtonEventArgs e);
}
public class GenericUserControl<T> : GenericUserControl
{
// generic properties and stuff
public GenericUserControl()
{
InitializeComponent();
}
}
// To use the GenericUserControl<T> in XAML, you could define:
public class GenericUserControlString : GenericUserControl<string> { }
// and use it in XAML, e.g.:
// <GenericUserControlString />
// alternatively you could probably (not sure) define a markup extension to instantiate
// it directly in XAML
}
Run Code Online (Sandbox Code Playgroud)
GenericUserControl.xaml
<UserControl x:Class="TestGenericUserControl.GenericUserControl"
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"
mc:Ignorable="d">
<Grid>
<Label Content="hello" />
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
不幸的是,XAML 不支持背后的通用代码,您可以绕过这个。
请参阅以下链接:
http://forums.silverlight.net/forums/p/29051/197576.aspx
我可以在 XAML(.NET 4 Framework 之前的版本)中指定泛型类型吗?
未来版本的 Visual Studuo 可能会通过 XAML 2009 原生支持通用控件。
| 归档时间: |
|
| 查看次数: |
11524 次 |
| 最近记录: |