微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Silverlight CheckBoxList

项目要用到复选框,但是在Silverlight中不存在CheckBoxList,通过查阅资料以及根据自己的理解,写了简单示例:

1.XAML

<UserControl x:Class="SilverlightApplication1.CheckBoxList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SilverlightApplication1" 
    xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400"> 
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox x:Name="lst">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <controlsToolkit:WrapPanel Orientation="Vertical" Height="30" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel> 
        </ListBox>
    </Grid>
</UserControl>

其中这里要引用Silverlight 3 Toolkit中的WrapPanel面板

xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"
2.CS 

namespace SilverlightApplication1
{
    public partial class CheckBoxList : UserControl
    {
        #region 属性注册
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.Register("ItemsSource",typeof(IEnumerable),typeof(CheckBoxList),new PropertyMetadata(null,ItemsSourceChanged));

        public static readonly DependencyProperty SelectedItemsProperty =
            DependencyProperty.Register("SelectedItems",new PropertyMetadata(null));

        public static readonly DependencyProperty displayMemberPathProperty =
            DependencyProperty.Register("displayMemberPath",typeof(string),new PropertyMetadata(string.Empty));

        private static ObservableCollection<InternalModel> _internalCollection; 

        /// <summary>
        /// 数据源
        /// </summary>
        public IEnumerable ItemsSource
        {
            get { return GetValue(ItemsSourceProperty) as ObservableCollection<object>; }
            set { SetValue(ItemsSourceProperty,value); }
        }

        /// <summary>
        /// 选择项
        /// </summary>
        public ObservableCollection<object> SelectedItems
        {
            get { return GetValue(SelectedItemsProperty) as ObservableCollection<object>; }
            set { SetValue(SelectedItemsProperty,value); }
        }

        /// <summary>
        /// 显示字段
        /// </summary>
        public string displayMemberPath
        {
            get { return GetValue(displayMemberPathProperty) as string; }
            set { SetValue(displayMemberPathProperty,value);
            if (value != null)
                lst.ItemTemplate =
                    (DataTemplate)XamlReader.Load(
                        @"<DataTemplate
                xmlns=""http://schemas.microsoft.com/client/2007"">
                <CheckBox Content=""{Binding Value." +
                        displayMemberPath +
                        @",Mode=TwoWay}"" IsChecked=""{Binding Selected,Mode=TwoWay}""/>
              </DataTemplate>");
            }
        }

        private static void ItemsSourceChanged(DependencyObject obj,DependencyPropertyChangedEventArgs e)
        {
            ((CheckBoxList)obj).BuildInternalCollection(e.NewValue as IEnumerable); 
        }

        private void BuildInternalCollection(IEnumerable collection)
        {
            _internalCollection = new ObservableCollection<InternalModel>();
            foreach (var obj in collection)
            {
                var nContainerItem = new InternalModel { Selected = false,Value = obj };
                nContainerItem.PropertyChanged += nContainerItem_PropertyChanged;
                _internalCollection.Add(nContainerItem);
            }
            lst.ItemsSource = _internalCollection;
        }

        void nContainerItem_PropertyChanged(object sender,PropertyChangedEventArgs e)
        {
            if (SelectedItems == null)
                SelectedItems = new ObservableCollection<object>();

            SelectedItems.Clear();

            foreach (var o in _internalCollection.Where(internalModel => internalModel.Selected))
                SelectedItems.Add(o.Value);
        }
        #endregion 
        public CheckBoxList()
        {
            InitializeComponent();  
            SelectedItems = new ObservableCollection<object>();
            
        } 
    }

    public class InternalModel : INotifyPropertyChanged
    {
        public object Value { get; set; }
        private bool _selected;
        public bool Selected
        {
            get { return _selected; }
            set
            {
                _selected = value;
                NotifyPropertyChanged("Selected");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

页面调用方法

1.XAML 

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SilverlightApplication1" 
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <local:People x:Key="folks"/> 
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDeFinitions>
            <RowDeFinition Height="400"></RowDeFinition>
            <RowDeFinition Height="40"></RowDeFinition> 
        </Grid.RowDeFinitions>
        <local:CheckBoxList x:Name="checkBoxlist" ItemsSource="{Binding AllPeople,Source={StaticResource folks},Mode=TwoWay}" displayMemberPath="Name"/>
        <Button Grid.Row="1" Content="显示选中项" Click="Button_Click" Width="60" HorizontalAlignment="Right" Margin="5"></Button>
    </Grid>
</UserControl>
2.CS

namespace SilverlightApplication1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender,RoutedEventArgs e)
        {
            string msg = string.Empty;
            ObservableCollection<object> list = checkBoxlist.SelectedItems;
            foreach (var obj in list)
            {
                Person per = obj as Person;

                msg += per.Name + "\n";
            }
            MessageBox.Show(msg);
        }
    }

    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }

    }

    public class People
    {
        public People()
        {
            AllPeople = (from a in Enumerable.Range(1,10)
                         select
                         new Person { ID = a,Name = "Name: " + a }
                     ).ToList();

        }
        public List<Person> AllPeople { get; set; }
    }
     
}


源码: Silverlight CheckBoxList

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐