实际项目中常常要实现有CheckBox列表框。但是WPF没有自带这样的一个控件,下面就用Style来实现这样的功能。而对于CheckBox列表框,又常常会有一个Select All的CheckBox来表示当前列表框的选择状态。这个功能也会被包含在下面的示例之中。效果如下图所示。

对于单纯的,没有后台数据绑定的情况下,这个功能可以用ItemContainerStyle来实现。代码如下:

CheckListBoxItemContainerStyle 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><Style x:Key="CheckListBoxItemContainerStyle"
TargetType="{x:Type ListBoxItem}">
<!--Set it un-focusable, becaues the CheckBox in it should be focusable and only it.-->
<Setter Property="Focusable" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<CheckBox Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTemplateSelector="{TemplateBinding ContentTemplateSelector}"
IsChecked="{Binding IsSelected, RelativeSource={RelativeSource TemplatedParent}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

CheckListBoxItemContainerStyle

其中要对Content和ContentTemplate等属性进行绑定,以方便对其进行扩展,保证其通用性。这个Style一般会放在Application级别的Resource中。

对于有后台数据绑定的情况,一般会有双个属性要绑定,一个是CheckBox里的Content,一个是CheckBox的IsChecked。绑定的路径,只有在用一个Style的ListBox那里才知道,所以并不能写在这个Style里,否则会破坏这个Style的通用性。比较合理的方式是基于这个现有的Style进行修改。

对于下面的数据类。

DataItem Class

public class DataItem : INotifyPropertyChanged {     private string name;     private bool isEnabled;
    public string Name     {         get { return name; }         set         {             name = value;             OnPropertyChanged("Name");         }     }
    public bool IsEnabled     {         get { return isEnabled; }         set         {             isEnabled = value;             OnPropertyChanged("IsEnabled");         }     }
    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
    protected virtual void OnPropertyChanged(string propertyName)     {         PropertyChangedEventHandler temp = PropertyChanged;         if (temp != null)         {             temp(this, new PropertyChangedEventArgs(propertyName));         }     } }

我们需要下面这个有针对性的Style来应用数据绑定。

DataItemCheckListBoxStyle 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><Style x:Key="DataItemCheckListBoxStyle"
TargetType="{x:Type ListBox}"
BasedOn="{StaticResource {x:Type ListBox}}">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}"
BasedOn="{StaticResource CheckListBoxItemContainerStyle}">
<Setter Property="IsSelected"
Value="{Binding IsEnabled}"/>
<Setter Property="Margin" Value="2,2,0,0"/>
</Style>
</Setter.Value>
</Setter>
<Setter Property="SelectionMode" Value="Multiple"/>
</Style>

DataItemCheckListBoxStyle

在上面的Style中,使用了ItemTemplate来指定CheckBox里的Content绑定到的属性,并把ListBoxItem的IsSelected绑定数据的相应属性上。由于这个Style是针对特定数据写的,所以应当放置在使用这个Style的ListBox所在的Window的Resource中。

当然,也可以为ListBox添加两个绑定类型的Attached Property来实现一个通用的Style。不过这个Property一样要在使用的地方设置,其实没有太大区别。有兴趣的读者可以自己试一下。

对于Select All这个CheckBox而言,用Attached Property倒是很方便。给CheckBox添加一个SyncTarget属性指向要同步的ListBox,就可以在Window.xaml.cs之外的地方同步CheckBox和ListBox了。代码如下:

ToggleButtonProperty 

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public class ToggleButtonProperty
{
// Using a DependencyProperty as the backing store for SyncTarget. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SyncTargetProperty =
DependencyProperty.RegisterAttached("SyncTarget", typeof(ListBox), typeof(ToggleButtonProperty), new UIPropertyMetadata(new PropertyChangedCallback(OnSyncTargetChanged))); public static ListBox GetSyncTarget(DependencyObject obj)
{
return obj.GetValue(SyncTargetProperty) as ListBox;
} public static void SetSyncTarget(DependencyObject obj, ListBox value)
{
obj.SetValue(SyncTargetProperty, value);
} private static void OnSyncTargetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
ToggleButton checker = sender as ToggleButton;
if (checker == null)
{
throw new InvalidOperationException("SyncTarget property only works on ToggleButton.");
} ListBox targetList = e.NewValue as ListBox;
if (targetList == null)
{
throw new InvalidOperationException("Sync target must be a ListBox.");
} //TODO: Un-subscribe OldValue's Event. checker.Checked += (s, a) =>
{
targetList.SelectAll();
}; checker.Unchecked += (s, a) =>
{
targetList.UnselectAll();
}; targetList.SelectionChanged += (s, a) =>
{
checker.IsChecked = targetList.SelectedItems.Count == ? false :
targetList.SelectedItems.Count == targetList.Items.Count ? (bool?)true : null;
};
}
}

ToggleButtonProperty

使用方式也很简单。如下代码所示。

用法

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--><DockPanel Margin="12">
<CheckBox Content="Select All"
Margin="0,0,0,5"
DockPanel.Dock="Top"
ext:ToggleButtonProperty.SyncTarget="{Binding ElementName=checkListBox}"/>
<ListBox x:Name="checkListBox"
Style="{StaticResource DataItemCheckListBoxStyle}"
ItemsSource="{Binding Path=Items, ElementName=mainWindow}"/>
</DockPanel>

用法

完整的项目文件可以从这里下载

转载至http://www.cnblogs.com/nankezhishi/archive/2009/12/30/checkablelistbox.html

CheckListBox的实现方式分析的更多相关文章

  1. 4.总结近5周以来的github上的工作情况,以图表方式分析你小组的工作情况、存在的问题及解决的方案。(尤心心)

    4.总结近5周以来的github上的工作情况,以图表方式分析你小组的工作情况.存在的问题及解决的方案. (1)利用github本身的graphs可以清晰的看出小组成员在github上面的交互,可以直接 ...

  2. apigw鉴权分析(1-3)百度 AI - 鉴权方式分析

    http://ai.baidu.com/docs#/Begin/top 一.访问入口 二.鉴权方式分析 1.鉴权认证方式一 - access_token - 针对HTTP API调用者 2.鉴权认证方 ...

  3. apigw鉴权分析(1-1)阿里数加 - 鉴权方式分析

    一.访问方式 1.访问阿里云首页 https://www.aliyun.com/?utm_medium=text&utm_source=bdbrand&utm_campaign=bdb ...

  4. Wps 2013 拼音标注两种方式分析

    Wps 2013 拼音标注两种方式分析 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转 ...

  5. Netty学习——Google Protobuf使用方式分析和环境搭建

    Google Protobuf使用方式分析 在RPC框架中,Google Protobuf是很常用的一个库,和Apache Thrift 是同款的用于进行序列化的第三方库.原理都是大同小异,无非就是使 ...

  6. 数据库join方式分析

    前言    不管是博客园还是CSDN,看到很多朋友对数据库的理解.认识还是没有突破一个瓶颈 ,而这个瓶颈往往只是一层窗纸,越过了你将看到一个新世界.    04.05年做项目的时候,用SQL Serv ...

  7. xamarin studio And linq 查询方式分析

    在 Windows 操作系统可以正常读取网络上的 https 数据流,在 Linux 操作系统中会失败:http://www.cnblogs.com/skyivben/archive/2012/03/ ...

  8. Apache Spark源码走读之7 -- Standalone部署方式分析

    欢迎转载,转载请注明出处,徽沪一郎. 楔子 在Spark源码走读系列之2中曾经提到Spark能以Standalone的方式来运行cluster,但没有对Application的提交与具体运行流程做详细 ...

  9. Android窗口管理服务WindowManagerService对窗口的组织方式分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/8498908 我们知道,在Android系统中, ...

随机推荐

  1. Grunt 新手指南

    导言 作为一个正在准备从java 后端转大前端,一直都有想着,在js 的世界里面有没有类似于maven或者gradle 的东西..然后,就找到了grunt 这玩意 Grunt是用来干什么的 诸如ant ...

  2. eclipse android logcat 只显示自己应用程序信息的设置方法

    1 elcipse 中往往会在logcat中显示 all message ,而这里面的信息太多,根本没有办法进行区分.如图: 2 我们想显示自己项目的 logcat .下面开始设置. 3 首先点击上面 ...

  3. brew 出现 git 错误的问题分析

    现象 brew update的时候出现 gitcrash   分析 在brew update 的时候看见有 git gc 的字样,提示有在gc 的动作.到/usr/local/ 目录,直接运行 git ...

  4. Navi.Soft30.开放平台.聚合.开发手册

    1系统简介 1.1功能简述 现在是一个信息时代,并且正在高速发展.以前获取信息的途径非常少,可能只有电视台,收音机等有限的来源,而现在的途径数不胜数,如:QQ,微信,官方网站,个人网站等等 本开发手册 ...

  5. mvc 方法只允许ajax访问

    有时候我们写一些方法 只想在ajax使用  其他的不想暴露  就可以对方法进行限制 如下: [AttributeUsage(AttributeTargets.Method)] public class ...

  6. ./adb: cannot execute binary file:

    问题描述: 在32位ubuntu(12.04)上下载了最新的android SDK,使用SDK manager 下载ADB之后发现,无法运行ADB命令,排除权限问题,在网上搜到答案: http://a ...

  7. 关于BigDecimal的使用

    为什么使用BigDecimal 使用BigDecimal首先要注意到float,double是无法支持商业计算的.只能支持工程计算.即误差允许的计算.通常float占用4个字节,32位.double占 ...

  8. Solr 5.x集成中文分词word,mmseg4j

    使用标准分词器,如图: 使用word分词器 下载word-1.3.jar,注意solr的版本和word分词的版本 将文件word-1.3.jar拷贝至文件夹C:\workspace\Tomcat7.0 ...

  9. WebDriver基本API使用手册(基于Java和C#)

    WebDriver基本API使用手册(基于Java和C#) http://www.docin.com/p-747728551.html

  10. vs2010 rdlc .net4.0 卸载 Appdomain 时出错。 (异常来自 HRESULT:0x80131015) 解决办法

    网上一看Appdomain出错,绝大部分都是说控件加载错误.经测试在.net 4.0环境下 rdlc报表很容易发生卸载 Appdomain 时出错. (异常来自 HRESULT:0x80131015) ...