Binding Observable collection list to dynamically created ComboBox in Silverlight

169 Views Asked by At

I have a requirement where I need to bind a list of observable collections to the item source of dynamically created ComboBoxes.

The problem is we bind through xaml conventionally in ItemsSource property but now the control rows in the grid are being added dynamically so each ComboBox in a row reference to the same collection whereas I need to bind it to a separate collection in observable collection list each time a row in the grid is added.

This what I have tried so far, any guidance would be appreciated. Thanks.

public virtual List<ObservableCollection<ComboBoxEntity>> ListRewardRule { get; set; }

Xaml :

<itimControls:ComboBox Name="cboReward"
                       IsMandatory="True"                           
                       itimComponents:ComponentManager.ComponentId="TXT_GROUP_RULE"
                       MaxWidth="400"
                       MinWidth="150"
                       ItemsSource="{Binding ListRewardRule, ElementName=RDefinitionScreen}"
                       DisplayMemberPath="Name"
                       SelectedValuePath="Code"
                       Loaded="cboReward_Loaded"
                       SelectedValue="{Binding RewardRuleId, Mode=TwoWay}"
                       SelectionChanged="cboReward_SelectionChanged">
</itimControls:ComboBox>

.CS :

private void cboReward_Loaded(object sender, RoutedEventArgs e)
{
    Itim.Framework.Silverlight.UI.Controls.ComboBox cboReward = ((Itim.Framework.Silverlight.UI.Controls.ComboBox)sender);
    int row = (int)cboReward.GetValue(Grid.RowProperty);
    if (Model.ListRewardRule.Count > 0)
    {
        var rewardGroups = Model.RewardGroupAndTier.RewardGroups;
        if(rewardGroups.Count > 1)
        {
            cboReward.ItemsSource = Model.ListRewardRule[row];               
        }
    }
}
1

There are 1 best solutions below

2
Paul Demesa On

The way I understand this is, you have a “grid” (I suppose you mean a DataGrid) and each row in the grid has, among other things, a set of combo boxes.

What I’d do is bind that grid to an ObservableCollection of a custom class, call it CustomRowClass. CustomRowClass should have an ObservableCollection that will be bound to the combo boxes.

The magic is to define a DataTemplate for CustomRowClass. Once you set up the XAML this way, all you need to do is create an instance of CustomRowClass, and then add it to the ItemsSource of the grid.