嗨我想動態綁定代碼中的DataGrid中的ComboBox。我看到了一些與此相關的答案,但沒有一個有幫助。一般的意見是使用DataTempleteColumn,但也沒有結果。這裏是我的代碼在代碼中綁定ComboBox到DataGrid
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Name="ButFill" Content="Fill Grid" HorizontalAlignment="Left" Height="22" Margin="373,65,0,0" VerticalAlignment="Top" Width="62"/>
<DataGrid x:Name="DaGrid" HorizontalAlignment="Left" Height="134" Margin="25,38,0,0" VerticalAlignment="Top" Width="289" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="text" Binding="{Binding Path=col1}"/>
<DataGridComboBoxColumn Header="combobox" Width="105" ItemsSource="{Binding Path=fill_items}"/>
<DataGridTemplateColumn Header="template combo" Width="105">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox Name="TempCombo" ItemsSource="{Binding Path=fill_items}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
和代碼背後,是
Imports System.Collections.ObjectModel
Class MainWindow
Public Property Table As New ObservableCollection(Of Test.dataset)()
Public Property fill_items As New ObservableCollection(Of String)
Private Sub ButFill_Click(sender As Object, e As RoutedEventArgs) Handles ButFill.Click
Dim temp As New Test.dataset()
Dim cb As New ComboBox
fill_items.Add("ItemNo1")
fill_items.Add("ItemNo2")
cb.ItemsSource = fill_items
temp.col1 = " Hello"
temp.col2 = cb
temp.col3 = cb
Table.Add(temp)
DaGrid.DataContext = Table
End Sub
End Class
Public Class dataset
Public Property col1 As String
Public Property col2 As ComboBox
Public Property col3 As ComboBox
End Class
我看到的問題是:
1)DataGridComboBox列這麼想的顯示,直到進入在編輯模式下。 2)組合框都是空的,但收藏「表」似乎有一個combobox.count爲2.
我做錯了什麼? 有人能告訴我一個合適的綁定ComboBox的完整示例嗎?
@FlorianGI,是的這種方式可行,但事情是在用戶在組合框中進行選擇之後,我需要在代碼中讀回它。我無法讀取所選項目,因爲它通常在組合框或datagrid列中完成。我可以通過什麼方式讀回選擇? – user2781366
在'dataset'中創建一個屬性,該屬性應該保存該值並將其綁定到COMBOBOX'SelectedItem屬性(Mode = TwoWay)。 –
@FlorianGI,是這樣嗎? '',公共財產項目作爲字符串?如果它是這樣的,那麼它不會被綁定爲我 –
user2781366