tags:

views:

38

answers:

2

I've been using WPF for a while now and I've gotten pretty used to many of the (rather daunting to the uninitiated) features: XAML, Binding, Templates, Triggers, etc. But I just can't seem to fully grasp the event system. Something that has gotten on my nerves from the very beginning is that events that are called 'changed' events (ie ListBox.SelectionChanged or TextBox.TextChanged) fire BEFORE the actual property they refer to is changed.

99% of the time I just want to respond to the user input event and see what the new value is. Very rarely do I actually need to respond before the control is updated to cancel the change or save the previous value or whatever.

It makes no sense to me to call these events "changed" events when the change has not yet fully occurred, it is still occurring. It would make a lot more sense at least to me to call these events "changing" events, and then a "changed" event would fire after all was updated.

Yes I know I can use the event args to determine what the new value will be, but this is incredibly annoying and usually requires lots of casting.

Is it too much to ask that when this code fires:

void myTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
     DoSomething(myTextBox.Text);
}

that myTextBox.Text have the NEW value of the text property. Am I just crazy? or am I missing something?

A: 

The behavior lets you reverse the change, and the extra flexibility comes with this pain point.

I feel your pain, but I don't think there's much to be done about it. Modify your code to read:

DoSomething(((TextBox)sender).Text);

...which is only slightly less clear, but is still all on one line.

Or, if you're paranoid about it:

       TextBox t = sender as TextBox;
       if (t!=null) DoSomething(((TextBox)sender).Text);

I imagine a lot of people will criticize the choice of event handling in the XAML code behind, in favor of an MVVM model, but that's a design decision for you to make, not them.

Rob Perkins
+1  A: 

The textbox in your example will have the new value if you subscribe to TextChanged. There is an event PreviewTextInput. This one will act as you described and you don't like.

Also SelectionChanged acts as the name implies. The only thing to take care about here is, that if you have a Binding (SelectedItem) and this has as target another control that is built async as for example the TreeView control or also ItemsControl-derivations, there may be a delay in requesting the destination property. But this does not seem the problem you describe.

HCL