【问题标题】:MVVM WPF - ComboBox two way binding inside ItemsControlMVVM WPF - ItemsControl 内的 ComboBox 两种方式绑定
【发布时间】:2015-08-25 09:15:45
【问题描述】:

我正在研究这个问题大约一天。

由于某种原因,如果 ComboBox 位于 ItemsControl 中,我无法将它绑定到 ComboBox。外面工作得很好。

我有一个 int 的 ObservableCollection?在我的 ViewModel 中:

    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 甚至设置了一些值,这些值显示在显示的 ComboBoxes 中。所以设置 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 属性(存储)时,它也不起作用。 我还尝试使用 SelectedItem 而不是 SelectedValue 并使用 Store 对象而不是 int 填充 ObservableCollection?。

【问题讨论】:

  • 这是相当混乱的措辞,并且缺乏重要信息。什么是“ScanRouter”、“Stores”,“Stores”上的“name”和“id”指向什么?我从来没有遇到过 ItemsControl 中的 ComboBoxes 的问题。我不认为使用 int 集合?一定是错的。

标签: wpf binding combobox itemscontrol selectedvalue


【解决方案1】:

问题是您将 ComboBox 的 SelectedValue 直接绑定到类型为 int ? 的集合元素。这不起作用,绑定目标必须是属性。尝试将您的 int ? 值包装在一个类中,并使用 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...

如果您仍有问题,请在此处回复。

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2010-11-06
    • 2011-10-28
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多