Richard
Richard

Reputation: 529

Binding a SelectedItem from a ComboBox from a seperate XAML control file

I have a ComboBox in an application Ribbon Menu, where the selected item binds to a theme of the application UI as follows:

Theme binding in MainWindow.xaml

Theme="{Binding SelectedItem.Tag, ElementName=_themeCombo}"

And the ComboBox

<ComboBox x:Name="_themeCombo" SelectedIndex="0" Width="200">
    <ComboBoxItem Content="Generic" />
    <ComboBoxItem Content="Aero">
        <ComboBoxItem.Tag>
            <xcad:AeroTheme />
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

The theme selection was working well, however, as the MainWindow.xaml is getting very long, I have moved my Menu Ribbon (and therefore the combobox) into a separate UserControl file named "Ribbon.xaml" and referenced it in as follows:

<local:Ribbon x:Name="RibbonWin" Grid.Row="0" />

This however, has broken the binding link for my theme selection. The Ribbon.xaml is in the same namespace as the mainwindow.xaml.

How do I provide a relative path to the ribbon ComboBox named “_themeCombo”?

I have tried placing the full address of the ComboBox in (inc class name of Ribbon) as follows, but this did not work:

Theme="{Binding SelectedItem.Tag, ElementName=DrainageDesign.View.Ribbon._themeCombo}"

Upvotes: 0

Views: 83

Answers (1)

grek40
grek40

Reputation: 13458

You can add a dependency property to your Ribbon UserControl and use it to transfer the value. Note you can use a more specific type than object for your actual Theme

public object SelectedTheme
{
    get { return (object)GetValue(SelectedThemeProperty); }
    set { SetValue(SelectedThemeProperty, value); }
}

public static readonly DependencyProperty SelectedThemeProperty =
    DependencyProperty.Register("SelectedTheme", typeof(object), typeof(Ribbon), new FrameworkPropertyMetadata());

Then bind the selected theme to the property

<local:Ribbon x:Name="RibbonWin"
              SelectedTheme="{Binding SelectedItem.Tag, ElementName=_themeCombo}"
              Grid.Row="0" />

And use the transferred value inside the Ribbon. I assume you give your Ribbon UserControl an internal name of _self for this example. You can actually use any technique of your choice to access the property within your control.

Theme="{Binding SelectedTheme, ElementName=_self}"

Upvotes: 0

Related Questions