起初,想添加TreeView的样式,在MouseOver时整行背景变色,但是我目前在XAML无法实现.

搜索了一下,有个方法在后台也要写代码.

参考:http://www.cnblogs.com/bray/archive/2010/05/01/1725457.html

用这个办法可以解决样式问题,但是不能方便的复用,就想到做成UserControl.

在UserControl里放入一个TreeView,需要 依赖属性ItemsSource 和 路由事件SelectedItemChanged

参考:http://www.cnblogs.com/zhouyinhui/archive/2007/10/27/939920.html

 

以下是我的部分代码

UCTreeView.xaml

 

View Code
<TreeView  x:Name="treeview1"  SelectedItemChanged="treeview1_SelectedItemChanged" Background="{x:Null}" />

 

 

UCTreeView.xaml.cs

 

View Code
 #region 属性依赖

        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource"typeof(IEnumerable), 
            typeof(UCTreeView),
            new PropertyMetadata(null,new PropertyChangedCallback(OnItemsSourceChanged)));
          
        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }

            set { SetValue(ItemsSourceProperty, value); }
        } 

        static void OnItemsSourceChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            if (sender != null && sender is UCTreeView)
            {
                UCTreeView source = (UCTreeView)sender;
                source.treeview1.ItemsSource = (IEnumerable)args.NewValue;
            }
             
        }
        #endregion

        #region 事件路由

        public static readonly RoutedEvent SelectedItemChangedEvent =
            EventManager.RegisterRoutedEvent("SelectedItemChanged", RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<object>), typeof(UCTreeView));

        [Description("选择项改变后发生")]
        public event RoutedPropertyChangedEventHandler<object> SelectedItemChanged
        {
            add
            {
                this.AddHandler(SelectedItemChangedEvent, value);
            }

            remove
            {
                this.RemoveHandler(SelectedItemChangedEvent, value);
            }
        }

        public void OnSelectedItemChanged(object oldValue, object newValue)
        {
            RoutedPropertyChangedEventArgs<object> arg =
                new RoutedPropertyChangedEventArgs<object>(oldValue, newValue, SelectedItemChangedEvent); 
            this.RaiseEvent(arg); 
        }

        private void treeview1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
               OnSelectedItemChanged((object)e.OldValue, (object)e.NewValue);

        }

        #endregion

 

posted on 2012-02-16 10:23  微星  阅读(1247)  评论(0编辑  收藏  举报