Patrick Vogt
Patrick Vogt

Reputation: 916

How to set the SelectedItem on a set of dynamically generated comboboxes

In my project I struggled at the task to set the SelectedItem on a set of dynamically generated comboboxes. I get always a NullReferenceException and I think this is caused by the binding between view and viewmodel.

Could anyone help me with some code snippets or just hints?

Here my XAML-Code:

<ItemsControl ItemsSource="{Binding TextBoxRowCollection}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <WrapPanel Margin="6,3,6,0">
                <ComboBox Name="SegmentBox" SelectedItem="{Binding Path=SelectedSegment, Mode=TwoWay}" ItemsSource="{Binding Path=SegmentList, Mode=TwoWay}" DisplayMemberPath="SegmentName" SelectedValuePath="SegmentFile" />
                <Border>
                    <TextBox Text="{Binding TextInput, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}" Width="136" MaxWidth="136" />
                </Border>
            </WrapPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

And here the C#-Code of my viewmodel:

Value value = ParamFileHelper.GetValue(DZParamFile, CellXCoord, CellYCoord);
ObservableCollection<TextBoxGridViewModel> textBoxCollection = new ObservableCollection<TextBoxGridViewModel>();
foreach (var linkage in value.Linkages)
{
    var tbgvm = (new TextBoxGridViewModel()).set(ModalDialogValueViewModel.Segments, ModalDialogValueViewModel);
    tbgvm.SelectedSegment = linkage.SelectedSegment;
    if (linkage.Text != null)
        tbgvm.TextInput = linkage.Text;
    else
    {
        tbgvm.FieldList = linkage.SelectedSegment.Fields;
        tbgvm.SelectedField = linkage.SelectedField;
        tbgvm.DZOperationList = ModalDialogValueViewModel.OperationList.OpList.Where(o => o.OpType == linkage.SelectedField.Type).ToList();
    }

    textBoxCollection.Add(tbgvm);
}
textBoxCollection[0].IsOperationVisible = Visibility.Hidden;

if (textBoxCollection.Count > 1)
    ModalDialogValueViewModel.IsRemoveButtonEnabled = true;

ModalDialogValueViewModel.IsOpen = true;

The exception is thrown when ModalDialogValueViewModel.IsOpen = true! The event OnPropertyChanged(...) is fired and the SelectedSegment-Property in the eventhandler is null:

void TextBoxGridViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if (e.PropertyName == "SelectedSegment" && !string.IsNullOrEmpty(SelectedSegment.SegmentName))
    {
        Console.WriteLine(SelectedSegment.SegmentName);
    }
}

Could anyone help me to set the SelectedItem in the comboboxes? Thank you in advance!

Upvotes: 0

Views: 95

Answers (1)

Babbillumpa
Babbillumpa

Reputation: 1864

Try using

SelectedValueBinding="{Binding SelectedSegment, Mode=TwoWay}"

instead of SelectedItem.

Upvotes: 1

Related Questions