原文:自定义Behavior 实现Listbox自动滚动到选中项

blend为我们提供方便的behavior来扩展我们的控件,写好之后就可以在blend中方便的使用了。

下面是自定义的behavior来实现Listbox自动滚动到选中项

其中this.AssociatedObject为使用该行为的控件。

其中

OnAttached()和OnDetaching()为必须重写的内容,通常可以在OnAttched()里面添加事件处理程序,来达到拓展的目的。

public class AutoScrollBehavior : Behavior<ListBox>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.SelectionChanged += new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
        }
        void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ListBox)
            {
                ListBox listbox = (sender as ListBox);
                if (listbox.SelectedItem != null)
                {
                    listbox.Dispatcher.BeginInvoke((Action)delegate
                    {
                        listbox.UpdateLayout();
                        listbox.ScrollIntoView(listbox.SelectedItem);
                    });
                }
            }
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.SelectionChanged -=
                new SelectionChangedEventHandler(AssociatedObject_SelectionChanged);
        }
    }

欢迎探讨WPF技术问题 QQ:281092346

最新文章

  1. CentOS 7 上安装 redis3.2.3安装与配置
  2. 20145209&amp;20145309信息安全系统设计基础实验报告 (3)
  3. java中身份证号15位转18位
  4. C#_Ajax_分页
  5. 基于2-channel network的图片相似度判别
  6. Dynamics CRM2013 Lookup Filtering using addCustomFilter
  7. 51nod1007-正整数分组(dp)
  8. 99%的Linux运维工程师必须要掌握的命令及运用
  9. sharepoint2013 Restore-SPSite 报错,采用数据库还原
  10. GRE封装解封装过程
  11. [C++ Primer Plus] 第3章、处理数据(一)程序清单
  12. L1 与 L2 正则化
  13. C++中位运算
  14. tips:Java中的switch的选择因子
  15. webservice调用dll
  16. list转map
  17. spring boot 配置动态刷新
  18. .NET Framework 4.0源代码
  19. java, android的aes等加密库
  20. Android ActionBar自定义

热门文章

  1. [Node] Run Local DevDependencies from the Command Line with npx
  2. 使用GDB进行嵌入式远程调试
  3. [RxJS] Replace zip with combineLatest when combining sources of data
  4. [Docker] Run, Stop and Remove Docker Containers
  5. 【solr基础教程之九】客户端 分类: H4_SOLR/LUCENCE 2014-07-30 15:28 904人阅读 评论(0) 收藏
  6. gradle导出依赖的jar包
  7. mount新磁盘
  8. [Win 8/WP 8]简单实现弹出页更换头像的功能
  9. PHP的SPL标准库里面的堆(SplHeap)怎么使用
  10. 将asp.net core2.0项目部署在IIS上运行