zoukankan      html  css  js  c++  java
  • ComboBox在WPF中的绑定示例:绑定项、集合、转换,及其源代码

    在WPF的Xaml中为ComboBox绑定数据时,由于参数很多,很容易混淆,在ListView中使用更是如此。本文通过对ComboBox在窗口和在ListView中绑定对象的属性和属性可能是枚举类型的情况进行简单讲解和示例,以作实际应用参照。

    源码可以到这里下载:ComboBoxBindings.rar

    1、ComboBox在窗口容器中的情况

    2、ComboBox在ListView中的情况

    3、绑定枚举

         示例中做枚举类型Sex的绑定时,先在Xaml中绑定值,然后在ComboBox的ItemsSouce中以String的方式枚举每个枚举值,形成Items的集合。这种方法是没问题,但在Xaml中枚举每个值,容易出错。

    其实枚举类型绑定可以做的更简单一些,就是在ComboBox的loaded时间中枚举并赋值ItemsSource,这个集合就是要绑定的枚举类型,而不是String类型:

         如在一个ListView中绑定Size属性:

         1、在后台代码中重写ComboBox的loaded事件,在里面将枚举类型以一个集合的形式绑定到ComboBox的ItemsSource:

    复制代码
    代码
            private void comboBoxSizeType_Loaded(object sender, RoutedEventArgs e)
            {
                List<RebarSize> items = new List<RebarSize>();
                items.Add(RebarSize.S3);
                items.Add(RebarSize.S4);
                items.Add(RebarSize.S5);
                items.Add(RebarSize.S6);
                items.Add(RebarSize.S7);
                items.Add(RebarSize.S8);
                items.Add(RebarSize.S9);
                items.Add(RebarSize.S10);
                items.Add(RebarSize.S11);
                items.Add(RebarSize.S14);
                items.Add(RebarSize.S18);

                ComboBox box = sender as ComboBox;
                box.ItemsSource = items;
            }
    复制代码

    这样,当ComboBox显示到界面时即可自动绑定ItemsSource = items。

         2、在Xaml中绑定:

              就一句话:SelectedValue="{Binding Path=Size, Mode=TwoWay}“,Ok了:

    复制代码
    代码
    <ListView Name="listView1"  Margin="20" BorderThickness="0,0,1,1">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Path=Name}"/>
                <GridViewColumn Header="Size">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox Name="comboBoxSizeType" Loaded="comboBoxSizeType_Loaded" MinWidth="60" BorderThickness="0"
                                      SelectedValue="{Binding Path=Size, Mode=TwoWay}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
    ...
    ...
    复制代码

    4、ItemsSource的RelativeSource绑定


    示例中的Xmal代码:

    Window1.xaml:

    复制代码
    代码
    <Window x:Class="ComboBoxBindings.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ComboBoxBindings"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="Window1" Height="402" Width="566">
        
        <Window.Resources>
            <ResourceDictionary>
                <local:EducationGradeConverter x:Key="educConverter"/>
            </ResourceDictionary>
        </Window.Resources>
        
        <Grid Margin="10">
            <StackPanel>
                <StackPanel Name="stackPanel1">
                    <TextBlock VerticalAlignment="Center" FontStyle="Italic" >ComboBox In Window:</TextBlock>
                    <TextBlock VerticalAlignment="Center" Foreground="#ff3300" >A dog's information</TextBlock>
                    <ComboBox VerticalAlignment="Center" HorizontalAlignment="Left" Width="120" Name="comboBoxInWnd" SelectionChanged="comboBoxInWnd_SelectionChanged"
                          DisplayMemberPath="Name"
                          ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Window1}}, Path=Dogs}">
                    </ComboBox>
                    <TextBlock VerticalAlignment="Center" Text="{Binding Path=Name}"></TextBlock>
                    <TextBlock VerticalAlignment="Center" Text="{Binding Path=Id}"></TextBlock>
                </StackPanel>
                
                <StackPanel>
                    <TextBlock VerticalAlignment="Center" FontStyle="Italic" >ComboBox In ListView:</TextBlock>
                    <TextBlock VerticalAlignment="Center" Foreground="#ff3300">Some people</TextBlock>
                    <ListView Name="listView1" MinHeight="200" >
                        <ListView.View>
                            <GridView>
                                <GridViewColumn Header="Index" DisplayMemberBinding="{Binding Path=Index}"/>
                                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
                                <GridViewColumn Header="Sex">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <ComboBox Width="120" SelectedValue="{Binding Path=Sex, Mode=TwoWay}" SelectedIndex="0">
                                                <ComboBox.Items>
                                                    <sys:String>Male</sys:String>
                                                    <sys:String>Female</sys:String>
                                                    <sys:String>Unknow</sys:String>
                                                </ComboBox.Items>
                                            </ComboBox>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Header="Education Grade">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <ComboBox Width="120" SelectedValue="{Binding Path=EducationGrade, Mode=TwoWay, Converter={StaticResource educConverter}}"
                                                  ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:Window1}}, Path=EducationTypes}">  //这里就是绑定了后台的集合对象实例,它是Window1的属性
                                            </ComboBox>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Header="My Dog">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <ComboBox Width="120" Loaded="comboBoxInListView_Loaded"
                                                  SelectedValue="{Binding Path=MyDog, Mode=TwoWay}"
                                                  SelectedValuePath="Id" DisplayMemberPath="Name">
                                            </ComboBox>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                            </GridView>
                        </ListView.View>
                    </ListView>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                <Button Margin="5" Click="btnAdd_Click" VerticalAlignment="Center" HorizontalAlignment="Left" Width="120" Height="28">Add</Button>
                <Button Margin="5" Click="btnDel_Click" VerticalAlignment="Center" HorizontalAlignment="Right" Width="120" Height="28">Delete</Button>
                    </StackPanel>
            </StackPanel>
        </Grid>
    </Window>

     
    复制代码


    Window1的后台代码:

    Window1.xaml.cs:

    复制代码
    代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.ComponentModel;

    namespace ComboBoxBindings
    {
        /// <summary>
        /// Interaction logic for Window1.xaml
        /// </summary>
        public partial class Window1 : Window
        {
            private int index;
            
            public Window1()
            {
                InitializeComponent();

                dogs.Add(new Dog("Dog1"));
                dogs.Add(new Dog("Dog2"));
                dogs.Add(new Dog("Dog3"));

                types.Add("EducationGrade1");
                types.Add("EducationGrade2");
                types.Add("EducationGrade3");

                this.listView1.ItemsSource = persons;
            }

            public List<String> types = new List<String>();
            public List<String> EducationTypes
            {
                get
                {
                    return types;
                }
            }

            public BindingList<Dog> dogs = new BindingList<Dog>();
            public BindingList<Dog> Dogs
            {
                get
                {
                    return dogs;
                }
            }

            public BindingList<Person> persons = new BindingList<Person>();
            public BindingList<Person> Persons
            {
                get
                {
                    return persons;
                }
            }

            private void comboBoxInListView_Loaded(object sender, RoutedEventArgs e)
            {
                ComboBox box = sender as ComboBox;
                box.ItemsSource = null;
                box.ItemsSource = dogs;
            }

            private void btnAdd_Click(object sender, RoutedEventArgs e)
            {
                persons.Add(new Person(++index));
            }

            private void btnDel_Click(object sender, RoutedEventArgs e)
            {
                while (this.listView1.SelectedItems.Count > 0)
                {
                    persons.Remove((Person)this.listView1.SelectedItems[0]);
                }
            }

            private void comboBoxInWnd_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                ComboBox box = sender as ComboBox;

                this.stackPanel1.DataContext = null;
                this.stackPanel1.DataContext = box.SelectedItem;
            }
        }
    }
  • 相关阅读:
    使用Apache搭建个人用户主页
    Linux搭建ftp服务器,并建立本地用户与虚拟用户
    Linux搭建FTP服务器,并建立匿名用户登录
    用虚拟机安装RHEL7
    基于OpenStack构建企业私有云(5)Neutron
    基于OpenStack构建企业私有云(3)Glance
    基于OpenStack构建企业私有云(1)实验环境准备
    基于OpenStack构建企业私有云(2)KeyStone
    python--003--百分号字符串拼接、format
    python--002--数据类型(set)
  • 原文地址:https://www.cnblogs.com/sjqq/p/7788987.html
Copyright © 2011-2022 走看看