當前位置:首頁 > IT技術(shù) > Web編程 > 正文

Silverlight CheckBoxList
2021-09-13 11:35:14

項目要用到復(fù)選框,可是在Silverlight中不存在CheckBoxList。通過查閱資料以及依據(jù)自己的理解,寫了簡單演示樣例:

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>
        /// 數(shù)據(jù)源
        /// </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));
            }
        }
    }
}

主頁面調(diào)用的方法

?

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 + "
";
            }
            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

?


?
?
?
?

本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務(wù)立即開通 >