Search code examples
c#wpfbindingcomboboxribbon

Binding a ribbon combobox to observable collection


I have a ribbon combob box as:

<r:RibbonComboBox DataContext="this"
                  SelectionBoxWidth="62"
                  VerticalAlignment="Center" 
                  IsEditable="True"  
                  Label="Saved Queries" 
                  Name="Saved_Queries"  
                  ToolTip="Select an item to run or edit" >
<r:RibbonGallery 
                  MaxColumnCount="1" 
                  Name="RibbonQu" 
                  ScrollViewer.VerticalScrollBarVisibility="Auto"
                  SelectionChanged="RibbonGallery_SelectionChanged" >
     <r:RibbonGalleryCategory ItemsSource="{Binding SavedXml}" >
            <r:RibbonGalleryItem Content="Green" Foreground="Green" />
            <r:RibbonGalleryItem Content="Blue" Foreground="Blue" />
            <r:RibbonGalleryItem Content="Orange" Foreground="Orange" />
     </r:RibbonGalleryCategory>
 </r:RibbonGallery>

I need to bind the items of the comobobox to an observable collection as follows:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("QueryList.xml");

        XmlNodeList List = doc.SelectNodes("//Query");

        foreach (XmlElement element in List)
        {

            if (element == null) return;
            if (element != null)
            {
                //Saved_Queries.Items.Add(element.InnerText);

                _savedxml.Add(element.InnerText.ToString());  
            }
        }
    }
    public ObservableCollection<string> SavedXml
    {
        get { return _savedxml; }
    set{}
    }

But i do not see anything in the comobox when i run it.I think the problem is with the data context, which has been set to others in the code, hence in the combobox i use : DataContext="this" but im still not able to achieve anything. how can i go about this? thanks!


Solution

  • As you suspected, you assign DataContext wrongly.

    If you need the combo to just have the items in SavedXml, and not actually need to set its DataContext, try removing DataContext="this" and adding ItemsSource="{Binding SavedXml, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}".

    If you do need to set the DataContext, change the assignment to: DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}" and then ItemsSource="{Binding SavedXml}".

    In both cases, since SavedXml is not a dependency property and it's not using INotifyProperty changed interface, you have to fill the items before InitializeComponent() is run. Event better: make SavedXml a DependencyProperty.