在我的项目中,我努力完成将一个动态生成的组合框设置为SelectedItem的任务。
我总是得到NullReferenceException
,我认为这是由视图和视图模型之间的绑定引起的。
任何人都可以帮我一些代码片段或只提示吗?
这是我的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>
这里是我的viewmodel的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
- 属性为null
:
void TextBoxGridViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "SelectedSegment" && !string.IsNullOrEmpty(SelectedSegment.SegmentName))
{
Console.WriteLine(SelectedSegment.SegmentName);
}
}
有人可以帮我在组合框中设置SelectedItem吗?提前谢谢!
答案 0 :(得分:1)
尝试使用
SelectedValueBinding =&#34; {Binding SelectedSegment,Mode = TwoWay}&#34;
而不是SelectedItem。