码迷,mamicode.com
首页 > 其他好文 > 详细

重写控件

时间:2015-10-15 09:52:10      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

自定义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());
        }

 

重写控件

标签:

原文地址:http://www.cnblogs.com/xlyg-14/p/4881313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!