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

本文转载自: https://www.cnblogs.com/khler/archive/2009/04/03/1428743.html 作者:khler 转载请注明该声明。

在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:

 

961ddebeb323a10fe0623af514929fc1.jpe 代码
         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了:

 

961ddebeb323a10fe0623af514929fc1.jpe 代码
< 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:

961ddebeb323a10fe0623af514929fc1.jpe 代码
< 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} " >
                                        
</ 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:

961ddebeb323a10fe0623af514929fc1.jpe 代码
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;
        }
    }
}

 


 

当然可以。以下是一个 DataGridComboBoxColumn 在 WPF 使用的示例,并绑定到数据源的代码: 1. 首先,你需要在 XAML 定义一个 DataGrid 控件,并在其添加模板列,以包含 DataGridComboBoxColumn: ```xml <DataGrid AutoGenerateColumns="False"> <DataGrid.Columns> <!-- other columns... --> <DataGridTemplateColumn Header="MyComboBox"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox ItemsSource="{Binding ItemsSource}" DisplayMemberPath="DisplayMember" SelectedValuePath="SelectedValue" SelectedValue="{Binding SelectedItem, Mode=TwoWay}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> ``` 2. 接下来,你需要在代码获取 DataGridComboBoxColumn,并将其绑定到数据源: ```csharp private void SetupDataGrid() { // get the DataGridComboBoxColumn var comboBoxColumn = dataGrid.Columns.First(c => c.Header.Equals("MyComboBox")) as DataGridComboBoxColumn; // setup the ItemsSource binding var binding = new Binding("MyItemsSource") { Source = this }; comboBoxColumn.ItemsSourceBinding = binding; // setup the DisplayMemberPath binding binding = new Binding("MyDisplayMemberPath") { Source = this }; comboBoxColumn.DisplayMemberPathBinding = binding; // setup the SelectedValuePath binding binding = new Binding("MySelectedValuePath") { Source = this }; comboBoxColumn.SelectedValuePathBinding = binding; // setup the SelectedValue binding binding = new Binding("MySelectedValue") { Source = this, Mode = BindingMode.TwoWay }; comboBoxColumn.SelectedValueBinding = binding; } // in your ViewModel or code-behind, define the following properties for each of the bindings: public IEnumerable MyItemsSource { get; set; } public string MyDisplayMemberPath { get; set; } public string MySelectedValuePath { get; set; } public object MySelectedValue { get; set; } ``` 这样就可以在 WPF 使用 DataGridComboBoxColumn 并绑定数据源了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值