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", typeof(IEnumerable), typeof(CheckboxList), new PropertyMetadata(null));

        public static readonly DependencyProperty DisplayMemberPathProperty =
            DependencyProperty.Register("DisplayMemberPath", typeof(string), typeof(CheckboxList), 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章