我正在尝试将ItemsSource绑定到RowDetailsTemplate中的ComboBox。如果我把一个ComboBox放在网格之外,它工作得很好。我认为这是因为网格上的ItemsSource属性可能会抛出RowDetailsTemplate中的ComboBox。XAML有什么想法吗?
Categories和CatTypes是两个不同的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;
}
}发布于 2011-03-24 21:12:03
如果您在VS中检查了调试输出,您将看到实际的绑定错误。下面的代码很可能会帮你解决这个问题。
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=CatTypes}" />如果你不能让RelativeSource工作,那就使用名字。属性CatTypes是某个类的属性,您为其创建了一个对象,并将其设置为某个控件的datacontext。只需为该控件指定一个名称(例如myControl),并像这样绑定:
<ComboBox ItemsSource="{Binding ElementName=myControl, Path=CatTypes}" />如果这不起作用,你需要发布更多的代码来找出你做错了什么。
发布于 2011-03-25 12:54:17
如果您尝试这样做,会发生什么?
<ComboBox DataContext="{Binding DataContext, ElementName=myControl}" ItemsSource="{Binding CatTypes}" />(当然,您需要重命名"myControl“以匹配窗口的名称。)
在这里,我们将组合框的数据上下文设置为与窗口的数据上下文相同。由于这也是XAML中第一个组合框的相同数据上下文,因此我认为第二个组合框的行为将开始与第一个类似。(尽管我担心这会导致一些不必要的数据库连接,每个网格行一个)。
再三考虑,如果需要在行的上下文中设置其他属性,则不希望设置整个ComboBox的数据上下文。在这种情况下,我会尝试这样的东西。
<ComboBox ItemsSource="{Binding ElementName=myControl, Path=DataContext.CatTypes}" SelectedItem="{Binding CategoryType}" />https://stackoverflow.com/questions/5419153
复制相似问题