WPF - Can List <t>可用作dependencyProperty </t>

时间:2012-12-04 18:32:31

标签: wpf generics reflection collections dependency-properties

我有一个简单的搜索文本框。此文本框充当过滤器。我现在已经复制/粘贴了第五次代码,足够了。时间进行自定义控制。

左右括号已替换为()

我的自定义控件很简单。我的问题是我想在这个类型为List(T)的控件上有一个dependencyProperty。

我创建了一个测试项目来证明它并确保它有效。它运作良好。忽略列表。

以下是全班。问题是,阻止我的唯一事情是用List(T)替换List(Person)。类似List的地方:T是Object

typeof(List(T)其中:T是Object)&lt; =很明显我不能这样做但是想一想我想要完成什么。

public class SearchTextBox : TextBox
{
    public static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register("FilterSource", typeof(List<Person>), typeof(SearchTextBox), new UIPropertyMetadata(null)); //I WANT THIS TO BE LIST<T>

    public List<Person> FilterSource
    {
        get
        {
            return (List<Person>)GetValue(SourceProperty);
        }
        set
        {
            SetValue(SourceProperty, value);
        }
    }

    public static readonly DependencyProperty FilterPropertyNameProperty =
        DependencyProperty.Register("FilterPropertyName", typeof(String), typeof(SearchTextBox), new UIPropertyMetadata());

    public String FilterPropertyName
    {
        get
        {
            return (String)GetValue(FilterPropertyNameProperty);
        }
        set
        {
            SetValue(FilterPropertyNameProperty, value);
        }
    }

    public SearchTextBox()
    {
        this.KeyUp += new System.Windows.Input.KeyEventHandler(SearchBox_KeyUp);
    }

    void SearchBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        ICollectionView view = CollectionViewSource.GetDefaultView(FilterSource);

        view.Filter = null;
        view.Filter = new Predicate<object>(FilterTheSource);
    }

    bool FilterTheSource(object obj)
    {
        if (obj == null) return false;

        Type t = obj.GetType();

        PropertyInfo pi = t.GetProperty(FilterPropertyName);

        //object o = obj.GetType().GetProperty(FilterPropertyName);

        String propertyValue = obj.GetType().GetProperty(FilterPropertyName).GetValue(obj, null).ToString().ToLower();

        if (propertyValue.Contains(this.Text.ToLower()))
        {
            return true;
        }

        return false;
    }
}

1 个答案:

答案 0 :(得分:12)

没有;那是不可能的。
相反,只需使用非通用typeof(IList)