MVVM WPF - ComboBox 双向绑定 ItemsControl

MVVM WPF - ComboBox two way binding inside ItemsControl

我现在正在处理这个问题大约一天。

出于某种原因,如果 ComboBox 在 ItemsControl 中,我无法将值双向绑定到 ComboBox。外面工作很好。

我有一个整数类型的 ObservableCollection?在我的视图模型中:

    private ObservableCollection<int?> _sorterExitsSettings = new ObservableCollection<int?>();
    public ObservableCollection<int?> SorterExitsSettings
    {
        get { return _sorterExitsSettings; }
        set
        {
            if (_sorterExitsSettings != value)
            {
                _sorterExitsSettings = value;
                RaisePropertyChanged("SorterExitsSettings");
            }
        }
    }

我的XAML:

<ItemsControl ItemsSource="{Binding SorterExitsSettings}">
<ItemsControl.ItemTemplate>
    <DataTemplate>
            <ComboBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, Path=DataContext.ScanRouter.Stores}"
                        SelectedValue="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="name" SelectedValuePath="id" IsEditable="True" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

因此 ComboBox 中填充了商店列表。到目前为止它工作正常。 ObservableCollection SorterExitsSettings 甚至设置了一些值,这些值显示在显示的组合框中。所以设置 SelectedValue 也有效。

但是,当我更改选择时,SorterExitsSettings 不会更改。当我在没有 ItemsControl 的情况下实现 ComboBoxes(100) 时,它突然工作正常。

<ComboBox ItemsSource="{Binding ScanRouter.Stores}" DisplayMemberPath="name" SelectedValuePath="id" IsEditable="True" SelectedValue="{Binding SorterExitsSettings[0], Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

当我使用 ItemsControl 和上面显示的示例 ComboBox 实现 ComboBox 时会更好。当我更改单个 ComboBox 的值时,它会更改 ItemsControl 内的 ComboBox 的值,但反过来不会。

以前有人遇到过这个问题吗?

我的猜测是 ItemsControl 不喜欢我将所选值绑定到列表中的项目这一事实。但是,当我直接绑定到 ViewModel 属性(Store) 时,它也不起作用。 我还尝试使用 SelctedItem 而不是 SelectedValue 并使用 Store 对象而不是 int 填充 ObservableCollection?

问题是您将 ComboBox 的 SelectedValue 直接绑定到 int ? 类型的集合元素。这行不通,绑定目标必须是属性。尝试将您的 int ? 值包装在 class 中,并将该值作为 class 的 属性 与 getter 和 setter 公开,即像这样:

private ObservableCollection<Wrapper> _sorterExitsSettings = new ObservableCollection<Wrapper>();
... etc...

并且:

public class Wrapper
{
    public int? Value {get; set;}
}

最后:

<ComboBox ... SelectedValue="{Binding Path=Value, Mode=TwoWay...

Post如果还有问题请返回此处。