![](/img/trans.png)
[英]DataGrid in DataGrid.RowDetailsTemplate with same ItemsSource (Current Item)
[英]Binding ComboBox ItemsSource in DataGrid RowDetailsTemplate
我試圖將ItemsSource
綁定到RowDetailsTemplate
的ComboBox
。 如果將ComboBox放置在網格外部,則可以正常工作。 我認為這是發生的,因為網格上的ItemsSource屬性可能會拋出RowDetailsTemplate中的ComboBox。 XAML有什么想法嗎?
類別和CatType是兩個不同的ObservableCollection
。
沒有錯誤發生; ComboBox只是顯示為空。
<ComboBox ItemsSource="{Binding CatTypes}"></ComboBox>
<my:DataGrid Name="gridProds" AutoGenerateColumns="False"
AlternatingRowBackground="Gainsboro" ItemsSource="{Binding Categories}">
<my:DataGrid.Columns>
<my:DataGridTextColumn x:Name="CatId" Header="CatID" Width="Auto" Binding="{Binding CategoryID}" />
<my:DataGridTextColumn Header="CatName" Width="Auto" Binding="{Binding CategoryName}" />
</my:DataGrid.Columns>
<my:DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label>ID:</Label>
<TextBox Name="txtGridCatId" Text="{Binding CategoryID}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Category Type:</Label>
<ComboBox ItemsSource="{Binding CatTypes}"></ComboBox>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</my:DataGrid.RowDetailsTemplate>
</my:DataGrid>
在名為DataSource的類中,完成以下操作:
private ObservableCollection<string> _cattypes = new ObservableCollection<string> { };
public ObservableCollection<string> CatTypes
{
get
{
_cattypes = new ObservableCollection<string> { };
SqlConnection con = new SqlConnection("MyConnStringHere;");
SqlCommand cmd = new SqlCommand("Select ID, CatType from PfCategoryType ORDER BY CatType", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string CatType = (string)rdr["CatType"];
_cattypes.Add(CatType);
}
con.Close();
return _cattypes;
}
}
在MainWindow.xaml.cs中,我有:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataSource dataSource = new DataSource();
this.DataContext = dataSource;
}
}
如果您在VS中檢查了調試輸出,則會看到實際的綁定錯誤。 下面的代碼很可能會為您修復它。
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=CatTypes}" />
如果您無法使RelativeSource工作,請使用名稱。 屬性CatTypes是某些類的屬性,您為該類創建了一個對象並將其設置為某個控件的數據上下文。 只需給該控件命名(例如myControl)並像這樣綁定即可:
<ComboBox ItemsSource="{Binding ElementName=myControl, Path=CatTypes}" />
如果這樣不起作用,則需要發布更多代碼,以弄清楚您在做什么錯。
如果您嘗試此操作會怎樣?
<ComboBox DataContext="{Binding DataContext, ElementName=myControl}" ItemsSource="{Binding CatTypes}" />
(當然,您已重命名“ myControl”以匹配窗口名稱。)
在這里,我們將組合框的數據上下文設置為與窗口的數據上下文相同。 由於這也是XAML中第一個組合框的數據上下文,因此我想第二個組合框將像第一個組合框一樣開始工作。 (盡管我擔心這會導致一些不必要的數據庫連接,每個網格行一個。)
再次考慮,如果您需要在該行的上下文中設置其他屬性,則不需要設置整個ComboBox的數據上下文。 在這種情況下,我會嘗試類似的方法。
<ComboBox ItemsSource="{Binding ElementName=myControl, Path=DataContext.CatTypes}" SelectedItem="{Binding CategoryType}" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.