C# 如何查找RibbonComboBox的子元素

C# 如何查找RibbonComboBox的子元素,c#,wpf,xaml,C#,Wpf,Xaml,我在XAML中声明了一个RibbonComboBox <RibbonGroup Header="Category"> <RibbonComboBox Name="cboCategory" Label="Category" HorizontalContentAlignment="Left"> <RibbonGallery Name="galCategory"> <RibbonGalleryCategory N

我在XAML中声明了一个RibbonComboBox

<RibbonGroup Header="Category">
    <RibbonComboBox Name="cboCategory" Label="Category" HorizontalContentAlignment="Left">
        <RibbonGallery Name="galCategory">
            <RibbonGalleryCategory Name="catCategory" DisplayMemberPath="Text">
            </RibbonGalleryCategory>
        </RibbonGallery>
    </RibbonComboBox>
    <RibbonComboBox Name="cboSubcategory" Label="Subcategory:" HorizontalContentAlignment="Left">
        <RibbonGallery Name="galSubcategory">
            <RibbonGalleryCategory Name="catSubcategory" DisplayMemberPath="Text">
            </RibbonGalleryCategory>
        </RibbonGallery>
    </RibbonComboBox>
</RibbonGroup>
但是,在编译此代码时,当我传递组合框时,VisualTreeHelper.GetChildrenCount始终返回0。因此它无法找到控件的子级

编辑:


通过名称VisualTreeHelper,我假设这个类用于查找可视元素,而gallery可能不是一个单独的可视元素。所以我想我需要知道如何遍历非可视的子元素。

我提出了两种不同的方法。一个是嵌套元素,另一个是简单的组合框。按钮填充并读取组合框和RibbonGalleryCategory

XAML

XAML


正如您所看到的,更多的功能,更少的代码:

您需要MVVM方法还是只需要代码隐藏?@lokusking:现在,我只是想从代码中找到元素。谢谢,但我仍然不知道在哪里,给定cboSubcategory的一个实例,我可以编写代码来查找galSubcategory。我知道我可以直接引用图库,但我需要能够从一个RibbonComboBox的引用中找到它。我将进入MVVM——我已经开始了解这一点。但是我真的需要总结一下我已经开始的一些代码。顺便说一句,我还注意到,当我像上面那样填充代码时,我无法从组合框中选择任何内容。这些项目会出现,当我将鼠标悬停在它们上面时,它们会高亮显示,但单击所选内容没有任何效果。@JonathanWood更新了我的见解潜入MVVM 2小时后,您将看到不同的结果。现在几乎不再需要像过去那样操纵控件了。将GUI业务留给GUI,重点放在功能上。我将提供一个例子作为编辑
protected T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj == null)
        return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        var child = VisualTreeHelper.GetChild(depObj, i);
        var result = (child as T) ?? GetChildOfType<T>(child);
        if (result != null)
            return result;
    }
    return null;
}
  <StackPanel>
            <Button Content="Fill me :)" Width="80" Height="20" Click="FillMe_OnClick"/>
            <Ribbon>
                <RibbonGroup Header="Category">
                    <RibbonComboBox Name="cboCategory" Label="Category" HorizontalContentAlignment="Left">
                        <ComboBoxItem>Item 1</ComboBoxItem>
                        <ComboBoxItem>Item 2</ComboBoxItem>
                        <ComboBoxItem>Item 3</ComboBoxItem>
                        <ComboBoxItem>Item 4</ComboBoxItem>
                    </RibbonComboBox>
                    <RibbonComboBox Name="cboSubcategory" Label="Subcategory:" HorizontalContentAlignment="Left">
                        <RibbonGallery Name="galSubcategory">
                            <RibbonGalleryCategory Name="catSubcategory" DisplayMemberPath="Text">
                            </RibbonGalleryCategory>
                        </RibbonGallery>
                    </RibbonComboBox>
                </RibbonGroup>
            </Ribbon>
            <Button Content="Read me" Width="80" Height="20" Click="ReadMeCat_OnClick"></Button>
            <Button Content="Read me too" Width="80" Height="20" Click="ReadMeCombo_OnClick"></Button>
</StackPanel>
public MainWindow()
        {

            InitializeComponent();
        }

        private void FillMe_OnClick(object sender, RoutedEventArgs e)
        {
            this.catSubcategory.Items.Add(new { Text = "Hello" });
            this.catSubcategory.Items.Add(new { Text = "World" });
            this.catSubcategory.Items.Add(new { Text = "Hello" });
            this.catSubcategory.Items.Add(new { Text = "Moon" });
        }

        private void ReadMeCat_OnClick(object sender, RoutedEventArgs e)
        {
            var result = catSubcategory.Items.Cast<dynamic>().Aggregate("", (current, xx) => (string) (current + (xx.Text + "\n")));
            MessageBox.Show(result);
        }

        private void ReadMeCombo_OnClick(object sender, RoutedEventArgs e)
        {
            var result = cboCategory.Items.Cast<ComboBoxItem>().Aggregate("", (current, xx) => current + (xx.Content.ToString() + "\n"));
            MessageBox.Show(result);
        }
public partial class MainWindow : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public MainWindow()
    {

        InitializeComponent();
        this.Ponies.Add(new Pony() { Id = 0, Color = Brushes.DeepSkyBlue, Name = "Slayer" });
        this.Ponies.Add(new Pony() { Id = 1, Color = Brushes.DeepPink, Name = "Murder" });
        this.Ponies.Add(new Pony() { Id = 2, Color = Brushes.Yellow, Name = "Brutal" });
        this.DataContext = this;
    }

    private ObservableCollection<Pony> _ponies = new ObservableCollection<Pony>();
    private Pony _selectedPony;
    public ObservableCollection<Pony> Ponies => this._ponies;


    public Pony SelectedPony {
        get { return _selectedPony; }
        set {
            if (this._selectedPony == value) return;
            _selectedPony = value;
            this.OnPropertyChanged("SelectedPony");
        }
    }
}

public class Pony : INotifyPropertyChanged
{
    public int Id { get; set; }
    private string _name;

    public string Name {
        get { return this._name; }
        set {
            this._name = value;
            this.OnPropertyChanged("Name");
        }
    }

    public Brush Color { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
<Window x:Class="MyNameSpace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        x:Name="root"
        Title="Try WPF!"
        mc:Ignorable="d">

    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Ribbon>
            <RibbonGroup Header="Category">
                <RibbonComboBox Label="Category" HorizontalContentAlignment="Left" >
                    <RibbonGallery SelectedItem="{Binding SelectedPony}">
                        <RibbonGalleryCategory ItemsSource="{Binding Ponies}" >
                            <RibbonGalleryCategory.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Name="tb" Text="{Binding Name}" Background="{Binding Color}"/>
                            </DataTemplate>
                            </RibbonGalleryCategory.ItemTemplate>
                        </RibbonGalleryCategory>
                    </RibbonGallery>
                </RibbonComboBox>                
            </RibbonGroup>
        </Ribbon>

    </Grid>
</Window>