I have a user control which I would like to add a dependency property of type Func so I can assign it a method handler in XAML. However, this will cause an XAMLParseException: 'Func`2' type does not have a public TypeConverter class. What am I doing wrong? Do I need to implement a TypeConverter for Func or is there a better way?
The Func Dependency Property in the user control (MyUserControl):
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));
Example of using the DP, XAML:
<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>
Code behind:
namespace FuncTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
SquareHandler = (arg => arg * arg);
DataContext = this;
}
public Func<int, int> SquareHandler { get; set; }
}
}