Andrew Riebe
Andrew Riebe

Reputation: 421

Complex late binding

I have the following dilemma. I have pulled data into a DataTable. That data is then bound to a ComboBox.ItemsSource in the designer. I have then created a user control with multiple text boxes, check boxes, and other things. Now, the user control will change, at runtime, depending on an option that the end-user selects.

What I need to figure out (and has been eluding me) is how to Bind the user controls' DataContext to the ComboBox.SelectedItem at runtime so that when the User Control is added, the user can then select something in the ComboBox and it updates all of the controls on the User Control.

Any help would be appreciated.

Additional Information:

Whenever the user clicks on an item in a listbox, the following code is run:

    /// <summary>
    /// Adds the passed user control to the appropriate grid location
    /// </summary>
    /// <param name="aUC"><seealso cref="System.Windows.Controls.UserControl"/> to add to the grid</param>
    private void AddControl ( UserControl aUC ) {

        // verifies that there are child controls, I can
        // get an error if I don't perform this check ebfore
        // attempting to remove all of the bindings
        if ( this.pnlControls.Children.Count > 0 )
            BindingOperations.ClearAllBindings ( this.pnlControls.Children [ 0 ] );

        // remove all of child controls from the grid
        this.pnlControls.Children.Clear ( );

        // here I attempt to beind the datacontext of the given user control
        // to the data context of the 
        BindingOperations.SetBinding ( aUC , UserControl.DataContextProperty , new Binding ( "SelectedItem" ) { Source = cbxReport } );

        // finally...add the control
        this.pnlControls.Children.Add ( aUC );
    }

Now, in the XAML of the User Control, I have the following textbox:

 <TextBox Grid.Column="1" Grid.ColumnSpan="5" Margin="2.5" DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext}" Text="{Binding Path='Report Title'}"/>

I think this is where it's not setup correctly. I put a breakpoint after this.pnlControls.Childre.Add(aUC); and the appropriate value is always in the DataContext property.

Upvotes: 0

Views: 131

Answers (1)

Andrew Riebe
Andrew Riebe

Reputation: 421

I figured out what the issue was. The AncestorType was set to the wrong thing...which means that I had been doing things correctly. Thanks!

Upvotes: 1

Related Questions