views:

1911

answers:

3

Hi, I need to set a dependency property on a control (Slider.Value) in my code without it triggering a ValueChanged event (since I set the value, not the user). What is the best way to handle this situation in WPF?

For clarification, what I am trying to do is hook up WPF sliders to a WinForms User Control. Currently in my app I have a ValueChanged event handler that passes the slider value to the WinForms control via a method call. The WinForms control (which is actually a wrapper around a native OpenGL window) needs to be able to dynamically change the slider based on it's internal calculations. To do this I use an abstraction of a slider (ISlider) , I instantiate a WPF-flavor of that slider in my app, and pass a handle to it's base to the WinForms control via a .NET property on the WinForms User Control. All of this is currently working, it's just that when the internal logic decides the slider needs to change, it calls ISlider::SetPos(), which then changes the WPF slider, which then triggers a ValueChanged event on the slider, and the handler for that event extracts the slider's position and passes it in to the WinForms control which originated the event in the first place. The suggestions by ligaz and Alan Le both seem like they should work, but I'm just not sure I'm going about this in the best way.

+1  A: 

One possible solution is to derive from Slider and override OnValueChanged(...). When you did not want to raise the event you should do nothing, otherwise you should call the base implementation.

ligaz
+1  A: 

Here's a simply workaround/hack. Add a boolean to keep track whether you changed the setting, let's say "IsChangedByMe". When you change the dependency property in code, set the bool to true. In the ValueChanged event, if IsChangedByMe is true, don't do anything.

Alan Le
+4  A: 

Are you sure you really want to do that? If there's a piece of UI databound to that property and you allow for changing the value without triggering the ValueChanged event you'd quickly end up with your UI no longer synchronized with the data.

In the case of your slider, imagine the user places it at 75%. Now your code changes it to 10% in the background but suppresses the change notification. It still looks on the screen like it's at 75% (since it wasn't told it changed), but it's being used as 10% by the code that's running. Sounds like a recipe for confusion.

Scott Bussinger
I see your point - I had not thought about the events also working in that direction. I will give more details in the question - maybe I'm going about this in the wrong way...
Brian Stewart