开发者

OnDataContextChanged method not available on WPF ListBox control

I want to execute some custom code whenever the datacontext for ListBox changes. I am using the ListBox control on multiple forms and want to achieve (execute same custom code) the same thing for all forms.

One alternative, which I thought of, was to derive from ListBox and override the DataContext property. But, I found that DataContext property is not virtual and hence cannot be overridden in the derived class. Also, there is no method like ‘OnDataContextChanged’ which could be overridden in the derived class.

There exists a DataContextChanged event on a ListBox control. The only option now is the derived class subscribing to the base class event, which I feel is not good, may be, because I have not done this before. Here is how it will look like:

public class PanningListBox : ListBox 
{
    public PanningListBox()
    {
        base.DataContextChanged += new DependencyPropertyChangedEventHandler(PanningListBox_DataContextChanged);
    }

    void PanningListBox_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
    {
        //Custom logic goes here
    }
}

Is the above mechanism viable? Are there any better alternatives? For other events (event) the ListBox control has equivalent virtual protected methods (OnEvent) that could be开发者_运维技巧 overridden in derived class. I wonder why the event design guideline is not being followed for DataContextChanged event? Why ‘OnDataContextChanged’ method is not available in the ListBox class?


It's fine to subscribe to the base class event, even though I usually find it more elegant to override the OnSomeEvent method. That's really just a question of style. Anyway, in that case you don't have the option to override the method... You could override OnPropertyChanged, as suggested by Markus Hütter, but that option isn't always available (not all events are related to a property change).


you can do an override of OnPropertychanged:

protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    if(e.Property == FrameworkElement.DataContextProperty)
    {
        //logic goes here
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜