Silverlight CheckBoxList,silverlight

來源:互聯網
上載者:User

Silverlight CheckBoxList,silverlight

項目要用到複選框,但是在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.