将功能区组合框绑定到可观察的集合

时间:2011-11-08 04:23:26

标签: c# wpf binding combobox ribbon

我有一个功能区组合框:

<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>

我需要将comobobox的项目绑定到一个可观察的集合,如下所示:

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{}
    }

但是当我运行它时,我在comobox中看不到任何内容。我认为问题出在数据上下文中,已经在代码中设置为其他内容,因此在我使用的组合框中: 的DataContext = “本” 但我仍然无法实现任何目标。我怎么能这样做?谢谢!

1 个答案:

答案 0 :(得分:1)

如您所料,您错误地分配了DataContext。

如果您需要组合使用SavedXml中的项目,而实际上不需要设置其DataContext,请尝试删除DataContext="this"并添加ItemsSource="{Binding SavedXml, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"

如果你需要设置DataContext,请将作业更改为:DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"然后ItemsSource="{Binding SavedXml}"

在这两种情况下,由于SavedXml不是依赖属性而且它没有使用INotifyProperty更改的界面,因此必须在运行 InitializeComponent()之前填充项。事件更好:将SavedXml设为DependencyProperty