WPF combox binding

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

后台代码:
    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>
    
{ }
努力奋斗
posted @ 2010-11-12 15:42  River.  阅读(1127)  评论(0编辑  收藏  举报