none
ComboBox的DropDown设置成TreeView的问题. RRS feed

  • 问题

  • 现在我需要改变一个ComboBox的DropDown,使得弹出的不是一个List,而是一个Tree.

    我尝试重写ComboBox的ControlTemplate,改写了

    http://msdn.microsoft.com/zh-cn/library/ms752094.aspx给出的ControlTemplate,将其中popup的

     <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
    改变成

    <TreeView    x:Name="treeView"
             ItemTemplate="{TemplateBinding ItemTemplate}"
             ItemsSource="{TemplateBinding ItemsSource}"
             DisplayMemberPath="{TemplateBinding DisplayMemberPath}"
             ScrollViewer.VerticalScrollBarVisibility="Disabled"
             ScrollViewer.HorizontalScrollBarVisibility="Disabled"

    local:ComboBoxExtensions:.SynchronizeWithOuterComboBox="true"

    />

    然后添加了类

    public class ComboBoxExtensions
        {
            public static bool GetSynchronizeWithOuterComboBox(DependencyObject obj)
            {
                return (bool)obj.GetValue(SynchronizeWithOuterComboBoxProperty);
            }

            public static void SetSynchronizeWithOuterComboBox(DependencyObject obj, bool value)
            {
                obj.SetValue(SynchronizeWithOuterComboBoxProperty, value);
            }

            public static readonly DependencyProperty SynchronizeWithOuterComboBoxProperty =
                DependencyProperty.RegisterAttached("SynchronizeWithOuterComboBox", typeof(bool), typeof(ComboBoxExtensions), new PropertyMetadata(OnSynchronizeWithOuterComboBoxChanged));


            private static void OnSynchronizeWithOuterComboBoxChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
            {
                (d as TreeView).SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(ComboBoxExtensions_SelectedItemChanged);
            }

            static void ComboBoxExtensions_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
            {
                TreeView treeView = sender as TreeView;
                ComboBox comboBox = treeView.TemplatedParent as ComboBox;

               comboBox.SelectedItem = treeView.SelectedItem;
                comboBox.IsDropDownOpen = false;
            }

    }
    }

    采用上述方法后,我目前可以显示出一个TreeView,但是在选择了一个二级节点后,ComboBox显示的仍然是其一级节点的值.换句话说,比如一个TreeItem为Item1,其下面又包含Item1.1,当我选择1.1后,显示的仍然是1.

    请问这样的情况该如何解决?谢谢!

    2010年6月9日 9:06

答案

全部回复