代码之家  ›  专栏  ›  技术社区  ›  Wallstreet Programmer

用户控件的Func属性

  •  2
  • Wallstreet Programmer  · 技术社区  · 14 年前

    我有一个用户控件,我想添加一个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; }
        }
    }
    
    1 回复  |  直到 14 年前
        1
  •  6
  •   Konstantin Oznobihin    14 年前
    MyFunc="SquareHandler"
    

    表示将“MyFunc”属性设置为“SquareHandler” 一串 这就是为什么它要求你有一个类型转换器,可以把字符串转换成func,把它改成

    <FuncTest:MyUserControl MyFunc="{Binding SquareHandler}" />
    

    使用当前DataContext的SquareHandler属性。