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;
否則,你會探索資料是綁上去了,但就是沒顯示,這也是我想不通的地方,如果你瞭解這方面的知識,請賜教,謝謝。