浮华过后,真金始现

一切问题最终都是时间问题,一切烦恼其实都是自寻烦恼
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[原创]ComboBox绑定DataTable

Posted on 2008-07-25 15:44  Kolor  阅读(4339)  评论(6编辑  收藏  举报

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;
否则,你会发现数据是绑上去了,但就是没显示,这也是我想不通的地方,如果你了解这方面的知识,请赐教,谢谢。