0
votes

I want to create element dynamically, so I use C# code behide to create a control.

Radio button was created and I want to bind some element with it (in this case, I use button).

Here is my source code

/*create radio button */

RadioButton secondaryRadio = new RadioButton()
    { 
        Name = "secondaryRadio_" + orderOfTransport + "_" + orderOfSubTransport,
        GroupName = "Transport_" + orderOfTransport + "_" + orderOfSubTransport,
        IsChecked = false,
     };

/*create bind object */

        Binding userChoice2 = new Binding("IsChecked")
        {
            ElementName = "secondaryRadio_" + orderOfTransport + "_" + orderOfSubTransport,
        };

/*create button and bind */

       Button outBoundButton = new Button()
        {

            Content = "Select",
            Name = "inb_button_" + orderOfTransport + "_" + orderOfSubTransport,
        };

        outBoundButton.SetBinding(Button.IsEnabledProperty, userChoice2);

and this is what got from Output window

Cannot find source for binding with reference 'ElementName=secondaryRadio_1_0'. BindingExpression:Path=IsChecked; DataItem=null; target element is 'Button' (Name='inb_button_1_0'); target property is 'IsEnabled' (type 'Boolean')

What I did wrong for this binding? Can I use binding object more than 1 time?

Many thanks for your help :D

2
Your binding error is telling you the binding can't find an element named "secondaryRadio_1_0" anywhere in the UI. Is that radio button added to the UI after its created? Other things to check is that the radio button exists somewhere in the VisualTree that the Button can access, and you may need to make sure the radio button is rendered prior to the binding being evaluated. - Rachel
What I did wrong for this binding? - Everything. Don't create or manipulate UI elements in code. WPF is not winforms. Learn MVVM. - Disclaimer: sorry for the rudeness and for being so straightforward, I'm just listening to Pantera. - Federico Berasategui
+1 for Pantera, not for the rudeness! - flq
@Rachel the problem has gone. Change elementname to source. Thanks for your help - neenutna
@HighCore thanks for your advice. I'm newbie for WPF. I have one question, How to create UI element on runtime with xaml ? - neenutna

2 Answers

3
votes

Instead of specifying the ElementName, you should directly specify the binding's Source:

Binding userChoice2 = new Binding("IsChecked")
{
    Source = secondaryRadio
};
0
votes

Regarding the ElementName: I cannot see that the two UIElements end up in some common Visual Tree - you can't expect this to work with two disparate objects.

as a word of advice it is almost always unnecessary to "dynamically" generate UIElements. Usually what you want to do is far more easily achieved with an ItemsControl and a DataTemplate for the Items and binding the ItemsSource to some objects.

If you really want to do WPF as you did Windows Forms, then you should follow Jon's advice.