【问题标题】:WPF TwoWay ComboBox binding not updatingWPF TwoWay ComboBox 绑定未更新
【发布时间】:2012-05-12 01:09:12
【问题描述】:

我创建了一个非常简单的 ViewModel,其中包含以下集合

 public ObservableCollection<Reader> Readers 
    { 
        get
        {
            if(_readers == null)
            {
                _readers = new ObservableCollection<Reader>();
            }

            return _readers;
        }

        set
        {
            _readers = value;
        }
    }

当数字选择器发生变化时,我会向集合中添加一个 Reader,如下所示:

_activeServer.Readers.Add(Readers.Instance.AllReaders[0]);

我已将 DataContext 设置为包含 Readers 集合的类,并尝试将 ComboBoxes 的 ListBox 绑定到项目,如下所示:

  <ListBox Name="_lbLanes"
                     BorderThickness="0"
                     Height="200"
                     ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                     ItemsSource="{Binding Readers}"    >
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <ComboBox Name="_cbReaders"
                              Margin="0,0,0,10"
                              ItemsSource="{Binding Source={x:Static models:Readers.Instance}, Path=AllReaders}"
                              DisplayMemberPath="Name"
                              SelectedItem="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                              MinWidth="400">
                        </ComboBox>
                    </DataTemplate>
                </ListBox.ItemTemplate>

                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Vertical"/>
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
            </ListBox>

您可以看到我正在绑定到自身,并且已将模式设置为 TwoWay。

我也试过将 SelectedValue 和 SelectedItem 绑定,都产生了以下问题...

当我单击保存提交页面时,我检查了该项目的 Readers 集合的内容,并且所有内容都设置为其初始值,该值等于 Readers.Instance.AllReaders[0] 我想如果我不想要双向绑定但我想要这将是正确的,这是可能的还是我必须去手动获取所有组合框中选择的项目?

提前感谢您抽出宝贵时间回复

丹

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    我认为你不能像这样绑定 TwoWay。

    也许this 就是你想要的。

    因为“双向绑定需要 Path 或 XPath”。并不意味着您应该将其设置为相同的值。您真的应该为您的 ListBox 创建特定对象,该对象将包含 Reader 作为属性。

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多