-1

I want to set style from code behind for GridView of ListView. Since that is ListView.View dependency property, I'd like to monitor for when it is changed.

Trying to add dependency property changed callback from this answer:

var handler = new DependencyPropertyChangedEventHandler(Handler);
DependencyPropertyDescriptor.FromProperty(ListView.ViewProperty,
    typeof(ListView)).AddValueChanged(listView, handler);

where handler is

void Handler(object sender, DependencyPropertyChangedEventArgs e) { ... }

will cause compiler error:

Error CS1503 Argument 2: cannot convert from 'System.Windows.DependencyPropertyChangedEventHandler' to 'System.EventHandler'

trying to cast (EventHandler)handler still keep compiler complaining:

Error CS0030 Cannot convert type 'System.Windows.DependencyPropertyChangedEventHandler' to 'System.EventHandler'


If I try to use standard event handler:

var handler = new EventHandler(Handler);

where

void Handler(object sender, EventArgs e) { ... }

makes it compilable, but then it will crash at run-time with

An unhandled exception of type 'System.ArgumentException' occurred in PresentationFramework.dll

Additional information: Handler type is not valid.

What else can I try to make AddValueChanged working with dependency property callback? Perhaps the approach is wrong, why? How else can I get notified when ListView.View is changed?

I don't want to apply either of solutions from this answer: can't use binding (value will be set in xaml) and don't want to make MyListView only for this.

Community
  • 1
  • 1
Sinatr
  • 20,892
  • 15
  • 90
  • 319

1 Answers1

2

This works for me:

public MainWindow()
{
    InitializeComponent();

    DependencyPropertyDescriptor
        .FromProperty(ListView.ViewProperty, typeof(ListView))
        .AddValueChanged(listView, ViewChanged);

    listView.View = new GridView();
}

private void ViewChanged(object sender, EventArgs e)
{
    Debug.WriteLine("ViewChanged");
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Thanks for checking, that was really helpful. The error indeed comes from another event handler (this makes my question poor), but the title + answer might be useful for someone else I guess. – Sinatr Oct 12 '17 at 09:40