【问题标题】:How to set the SelectedItem on a set of dynamically generated comboboxes如何在一组动态生成的组合框上设置 SelectedItem
【发布时间】:2015-02-13 19:36:06
【问题描述】:

在我的项目中,我努力在一组动态生成的组合框上设置 SelectedItem。 我总是得到一个NullReferenceException,我认为这是由视图和视图模型之间的绑定引起的。

谁能帮我一些代码 sn-ps 或只是提示?

这是我的 XAML 代码:

<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>

这里是我的视图模型的 C# 代码:

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;

ModalDialogValueViewModel.IsOpen = true! 时抛出异常!事件OnPropertyChanged(...) 被触发,事件处理程序中的SelectedSegment-Property 为null

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

谁能帮我在组合框中设置 SelectedItem?提前谢谢!

【问题讨论】:

    标签: c# .net wpf mvvm combobox


    【解决方案1】:

    尝试使用

    SelectedValueBinding="{绑定 SelectedSegment, Mode=TwoWay}"

    而不是 SelectedItem。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 2017-04-26
      • 2012-04-03
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多