[原創]ComboBox綁定DataTable

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.