开发者

WPF Combo Box Binding Issue

I'm trying to bind a ObservableCollection of a class to a combo box inside a datagrid.

public class ProductContainer
{
    public string Product { get; set; }
    public List<string> SubProducts { get; set; }

    public ProductContainer()
    {
        SubProducts = new List<string>();
    }
}

In my MainWindow.xaml i have the list.

public ObservableCollection<ProductContainer> Products { get; set; }

I'm trying to add it to a combo box to a datagrid with what i have, but it's not binding properly. What would the xaml look like?


<DataGrid AutoGenerateColumns="False" Name="ProductGrid" Width="Auto"
          AlternatingRowBackgr开发者_如何学编程ound="LightSlateGray" SelectionMode="Single" SelectionUnit="FullRow"  CanUserAddRows="True" CanUserDeleteRows="True" CurrentCellChanged="ProductGrid_CurrentCellChanged">
    <DataGrid.Resources>
        <DataTemplate x:Key="editProductTemplate">
            <ComboBox x:Name="cbProducts" ItemsSource="{Binding Path=Products, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" SelectedItem="{Binding Product}" SelectedValuePath="Product" DisplayMemberPath="Product"/>
        </DataTemplate>
        <DataTemplate x:Key="editSubProductTemplate">
            <ComboBox ItemsSource="{Binding Product.SubProducts, UpdateSourceTrigger=PropertyChanged}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTemplateColumn MinWidth="120"
            Header="Product"              
            CellTemplate="{StaticResource editProductTemplate}" />
        <DataGridTemplateColumn MinWidth="120"
            Header="SubProduct"                          
            CellTemplate="{StaticResource editSubProductTemplate}"/>
    </DataGrid.Columns>
</DataGrid>

This the xaml for it. The first combo box populates but the second one never populates based on whats in the first one, or shows anything at all.


Depends on the DataContexts. For info on how to debug bindings see MSDN, that is always useful and there are related questions which may help you both in constructing the right binding and avoiding ones that fail:

  • How to bind a DataGridComboBoxColumn outside the ItemSource
  • WPF Datagrid ComboBox DataBinding

The path in your second ComboBox.ItemsSource should probably just be SubProducts as your object's Product property is just a string. Further your classes should implement INotifyPropertyChanged so that the UI can be notified of any changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜