我有一个用户控件,我想添加一个Func类型的依赖属性,以便在XAML中为它分配一个方法处理程序。但是,这将导致XAMLParseException:'Func`2'类型没有公共TypeConverter类。我做错什么了?我需要为Func实现TypeConverter还是有更好的方法?
用户控件(MyUserControl)中的Func依赖项属性:
public Func<int, int> MyFunc
{
get { return (Func<int, int>)GetValue(MyFuncProperty); }
set { SetValue(MyFuncProperty, value); }
}
public static readonly DependencyProperty MyFuncProperty =
DependencyProperty.Register("MyFunc",
typeof(Func<int, int>),
typeof(SillyCtrl),
new UIPropertyMetadata(null));
<Window x:Class="FuncTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:FuncTest="clr-namespace:FuncTest"
Title="Window1" Height="300" Width="300">
<Grid>
<FuncTest:MyUserControl MyFunc="SquareHandler" />
</Grid>
</Window>
代码隐藏:
namespace FuncTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
SquareHandler = (arg => arg * arg);
DataContext = this;
}
public Func<int, int> SquareHandler { get; set; }
}
}