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

时间: 2024-08-03 02:07:15

ComboBox在WPF中的绑定示例:绑定项、集合、转换,及其源代码的相关文章

WPF中一个控件绑定另一个控件的属性

原文:WPF中一个控件绑定另一个控件的属性 如同一个Grid中的一个按钮根据另一个按钮的显示与否作出不同的响应: 绑定的时候通过ElementName来指定控件 <Grid Margin="50,130"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="40"/> </Grid.ColumnDefinitions>

WPF 在使用 ItemsSource 之前,项集合必须为空

原文:WPF 在使用 ItemsSource 之前,项集合必须为空 <DataGrid x:Name="datagrid" ItemsSource="{Binding ElementName=Mwindow, Path=Preson}" Margin="0,0,0,20"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Name}"

在WPF中如何使用RelativeSource绑定

在WPF绑定的时候,指定绑定源时,有一种办法是使用RelativeSource. 这种办法的意思是指当前元素和绑定源的位置关系. 第一种关系: Self 举一个最简单的例子:在一个StackPanel中,有一个TextBlock. <TextBlock FontSize="18" FontWeight="Bold" Margin="10" Background="Red" Width="80" Hei

WPF中的Command事件绑定

在项目中使用Command绑定能够使我们的代码更加的符合MVVM模式.不了解的同学可能不清楚,只有继承自ButtonBase类的元素才可以直接绑定Command(Button.CheckBox.RadioButton等) <Button Content="Normal" Command="{Binding NormalEventCommand}" ></Button> 如果我们要处理Label或者其他的一些控件,那么只能在走事件: <L

WPF中多个RadioButton绑定到一个属性

如图样: 在View中: <RadioButton IsChecked="{Binding Option, Converter={cvt:EnumToBooleanConverter},ConverterParameter={x:Static enum:RadionButtonOptions.One}}" Content="One" DockPanel.Dock="Top"/> <RadioButton IsChecked=&q

利用Powershell快速对WPF的ListBox 数据源的绑定

有时候,我们在封闭的环境中做开发工作,并没有那么多便捷的开发工具,只能利用当前系统自带的基本工具做开发, 比如利用强大的framework,而powershell就是很好的开发工具,在不安装visual studio的情况下,就能实现大部分功能. 下面就用一个简单的例子来实现WPF中ListBox 数据源的绑定 1.关于dataset,我就不做多解释了,简单来说,就是一个或多个DataTable 对象的集合. 用powershell来实现的话,是简单不过的事情了. #Create Table o

整理:WPF中Binding的几种写法

目的:整理WPF中Bind的写法 <!--绑定到DataContext--> <Button Content="{Binding DataTime}"/> <!--绑定到DataContext,并设置绑定模式--> <Button x:Name="btn" Content="{Binding DataTime,Mode=OneTime}"/> <!--绑定到DataContext,并设置更新模

在WPF中使用变通方法实现枚举类型的XAML绑定

问题缘起 WPF的分层结构为编程带来了极大便利,XAML绑定是其最主要的特征.在使用绑定的过程中,大家都普遍的发现枚举成员的绑定是个问题.一般来说,枚举绑定多出现于与ComboBox配合的情况,此时我们希望实现的目标有: 建立选择项与ItemsSource的对应关系: 自动获取用于ItemsSource的枚举源: 自定义下拉框中显示的内容. 对于目标1,考虑最简单的模式,即枚举的定义采用从0开始的连续整数,可以使用IValueConverter接口来实现从枚举到整型的双向转换,以使得枚举成员绑定

MVVM模式解析和在WPF中的实现(三) 命令绑定

MVVM模式解析和在WPF中的实现(三) 命令绑定 0x00 命令绑定要达到的效果 命令绑定要关注的核心就是两个方面的问题,命令能否执行和命令怎么执行.也就是说当View中的一个Button绑定了ViewModel中一个命令后,什么时候这个Button是可用的,按下Button后执行什么操作.解决了这两个问题基本就实现了命令绑定.另外一个问题就是执行过程中需要的数据(参数)要如何传递.本次主要探讨这几个问题. 0x01 命令绑定的实现 自定义一个能够被绑定的命令需要实现ICommand接口.该接