重写控件

自定义ListBox类
C# code

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 public class myListBox : System.Windows.Controls.ListBox
    {
        protected override DependencyObject GetContainerForItemOverride()
        {
            return new myListBoxItem();
        }
 
    }
    public class myListBoxItem : System.Windows.Controls.ListBoxItem
    {
        protected override void OnSelected(System.Windows.RoutedEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;
 
            while ((dep != null) && !(dep is ListBoxItem))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }
 
            if (dep == null)
                return;
 
            ListBoxItem item = (ListBoxItem)dep;
         
            if (item.IsSelected)
            {
                item.IsSelected = !item.IsSelected;
                //e.Handled = true;
            }
            base.OnSelected(e);
        }
    }

页面引用
C# code
?
1
2
3
4
5
  xmlns:control="clr-namespace:wpf.DependencyControl"
 
// 在Grid 中写
  <control:myListBox x:Name="myListBox" Width="100" Height="100" SelectionMode="Single" 
                               SelectionChanged="myListBox_SelectionChanged">

// 后台cs代码
C# code
?
1
2
3
4
5
6
7
 private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            object o = myListBox.SelectedItem;
            if (o == null)
                return;
            MessageBox.Show(o.ToString());
        }

 

posted @ 2015-10-15 08:41  西楼月光  阅读(156)  评论(0编辑  收藏  举报