ComboBox绑定DataTable

Xaml确实是个好东西,层次感非常强,一目了然。下面就是一个ComboBox的下例子:

< ComboBox  Height ="23"  HorizontalAlignment ="Left"  Margin ="0,11,0,0"  Name ="comboBox1"  VerticalAlignment ="Top"  Width ="120"  ItemsSource =" {Binding} "  SelectedIndex ="0" >
    
< ComboBox.ItemTemplate >
        
< DataTemplate >
            
< TextBlock  Text =" {Binding Path=Name} " />
        
</ DataTemplate >
    
</ ComboBox.ItemTemplate >
</ ComboBox >

绑定时,只需要指定其DataContext为一个DataTable实例即可。
Xaml简洁精练,那么我们再来看看用C#代码是怎么做到绑定的呢,请看下面动态添加一个ComboBox例子:

private   void  Window_Loaded( object  sender, RoutedEventArgs e)
{
    DataTable dt 
=   new  DataTable();
    dt.Columns.Add(
" Name " );
    dt.Rows.Add(
" just " );
    dt.Rows.Add(
" for " );
    dt.Rows.Add(
" test " );

    ComboBox cmb 
=   new  ComboBox();
    cmb.Width 
=   120 ;
    cmb.Height 
=   50 ;
    
    DataTemplate dataTemplate 
=   new  DataTemplate();
    FrameworkElementFactory f 
=   new  FrameworkElementFactory( typeof (TextBlock));
    f.SetBinding(TextBlock.TextProperty, 
new  Binding( " Name " ));
    dataTemplate.VisualTree 
=  f;
    cmb.ItemTemplate 
=  dataTemplate;
    cmb.ItemsSource 
=  dt.DefaultView;
    
    grid.Children.Add(cmb);
}
这里有点需要注意的是,为动态生成的ComboBox的ItemsSource指定DataTable数据源时,
不能直接指定cmb.ItemsSource = dt.Rows;而是要用cmb.ItemsSource = dt.DefaultView;
否则,你会发现数据是绑上去了,但就是没显示,这也是我想不通的地方,如果你了解这方面的知识,请赐教,谢谢。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值