Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Can List<T> be used as a dependencyProperty

I have a simple search text box. This text box acts as a filter. I've now copied/pasted the code for the 5th time and enough is enough. Time for a custom control.

left and right brackets have been replaced with ()

My custom control will be simple. My problem is I want to have a dependencyProperty on this control that is of type List(T).

I created a test project to proof it out and make sure it works. It works well. Ignore List.

Below is the entire class. The problem is that the only thing holding me up is replacing List (Person) with List(T). Something like List where: T is Object

typeof(List(T) where: T is Object) <= Obviously I can't do that but gives an idea what I'm trying to accomplish.

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;
    }
}
like image 453
tronious Avatar asked Dec 04 '12 18:12

tronious


Video Answer


1 Answers

No; that's not possible.
Instead, just use the non-generic typeof(IList).

like image 55
SLaks Avatar answered Oct 20 '22 14:10

SLaks