WPF开发中遇到的问题及解决系列(二):如何获取通过binding生成的ComboBox或者ListBox等的Item

将ComboBox绑定到数据源时,通常需要访问ComboBoxItem以执行某个操作。 可以通过使用ItemContainerGenerator来获取ComboBoxItem。
Xaml代码如下:

< Grid >
        
< ComboBox  Height ="40"  Margin ="52,59,66,0"  Name ="cbTest"  VerticalAlignment ="Top"  IsSynchronizedWithCurrentItem ="True"  SelectionChanged ="cbTest_SelectionChanged"  ItemsSource =" {Binding} " >
            
< ComboBox.ItemTemplate >
                
< DataTemplate >
                    
< TextBlock  Text =" {Binding Path=Name} " />
                
</ DataTemplate >
            
</ ComboBox.ItemTemplate >
        
</ ComboBox >
    
</ Grid >
后台代码:
     public   partial   class  Window1 : Window
    
{
        
public Window1()
        
{
            InitializeComponent();
        }


        
private void Window_Loaded(object sender, RoutedEventArgs e)
        
{
            Family family 
= new Family();
            
for (int i = 0; i < 10; i++)
            
{
                Person p 
= new Person();
                p.Name 
= "Name" + i.ToString();
                family.Add(p);
            }

            
this.cbTest.DataContext = family;
        }


        
private void cbTest_SelectionChanged(object sender, SelectionChangedEventArgs e)
        
{
            
//通过如下代码得到ComboBoxItem,然后对其进行操作
            ComboBoxItem cbItem = (ComboBoxItem)this.cbTest.ItemContainerGenerator.ContainerFromIndex(this.cbTest.SelectedIndex);
            
if (cbItem != null)
            
{
                cbItem.Background 
= Brushes.Red;
            }

        }

    }


    
public   class  Person
    
{
        
public string Name
        
{
            
get;            
            
set;
        }

    }

    
public   class  Family : ObservableCollection < Person >
    
{ }
详见MSDN: http://msdn2.microsoft.com/zh-cn/library/system.windows.controls.itemcontainergenerator.aspx

你可能感兴趣的:(combobox)