tags:

views:

55

answers:

3

I have two data-bound text boxes. One is bound to a string and the other to a number. The 'default' binding is set in XAML. Under some circumstances I need to reverse the bindings at runtime (the string is usually a prefix but sometimes it's a suffix). I have the following code in my view model, called when the window is loaded:

Binding stringBinding = BindingOperations.GetBinding(view.seqLeft, TextBox.TextProperty);
Binding numberBinding = BindingOperations.GetBinding(view.seqRight, TextBox.TextProperty);
view.seqLeft.SetBinding(TextBlock.TextProperty, numberBinding);
view.seqRight.SetBinding(TextBlock.TextProperty, stringBinding);

After that the code loads the properties to which the binding refers.

The problem is that the 'new' binding doesn't seem to work. What have I missed? Is there a better way?

+2  A: 

I might consider exposing Prefix and Suffix strings to which View can bind, then use logic within the ViewModel, or whatever backing object you're using, to fill those strings accordingly. This option neatly segments the business concern from the visual and simplifies what you have to keep track of in your view.

Ed Gonzalez
The view model exposes string and int properties and the controls are bound to them. Sometimes they need to be the other way round - what could be simpler? the view doesn't have to do anything (it only has InitializeComponent, no other code).I have discovered that neither SetBinding nor ClearBinding have any effect - whatever you do the original binding remains in place.I'm using VS2010RC and Framework 4 in case it's relevant.
Phil J Pearson
Phil, switching the bindings may be a valid approach, but I feel that changing the data, instead of the bindings, is a more elegant solution. I take the philosophy that we're exposing a prefix and suffix, instead of exposing a number and a string. To each his own.To help debug the binding swap issue, try checking the return value of SetBinding to see if there has been an error and validate that the Status is Active.
Ed Gonzalez
A: 

Why monkey around with the bindings at all? If you want to have a TextBox that's bound to one of two different things, create two TextBoxes, put them in the same location, and toggle their visibility based on whatever your swap condition is.

Robert Rossney
I've fixed it. Swapping binding works perfectly. I used to use visibility toggling in Windows Forms and ordinary Windows code but it makes the form/view design so messy I don't like it.I'm entirely happy with swapping binding now that it works!
Phil J Pearson
A: 

The only thing wrong with my code was the Text*Block*.TextProperty in the SetBinding calls! They should, of course, have been Text*Box*.TextProperty but I'd messed with it so long I wasn't seeing the wood for the trees.

Phil J Pearson