0

我有一个组合框,其 ItemsSource 属性绑定到 ObservableCollection 属性,其 SelectedIndex 属性分别绑定到整数属性。

<ComboBox Name="cmbDealt" ItemsSource="{Binding Path=DealList, Mode=TwoWay}" SelectedIndex="{Binding Mode=TwoWay, Path=DealIndex}"></ComboBox>
<CheckBox IsChecked="{Binding Mode=TwoWay, Path=SomeCondition}" Content="Some Condition"></CheckBox>

我的数据结构看起来像

 private ObservableCollection<string> m_DealList = null;
    private int m_DealIndex = 0;
    private bool m_SomeCondition = false;

    public ObservableCollection<string> DealList
    {
        get
        {
            if (m_DealList == null)
                m_DealList = new ObservableCollection<string>();
            else
                m_DealList.Clear();

            if (m_SomeCondition)
            {
                m_DealList.Add("ABC");
                m_DealList.Add("DEF");
            }
            else
            {
                m_DealList.Add("UVW");
                m_DealList.Add("XYZ");
            }
            return m_DealList;
        }
    }

    public int DealIndex
    {
        get { return m_DealIndex; }
        set
        {
            if (value != -1)
            {
                m_DealIndex = value;
            }
        }
    }

    public bool SomeCondition
    {
        get { return m_SomeCondition; }
        set
        {
            m_SomeCondition = value;
            OnPropertyChanged("DealList");
            OnPropertyChanged("DealIndex");
        }
    }

现在应用程序加载成功。但是,当用户将 ComboBox 的 SelectedIndex 从 0 更改为 1,然后选中复选框(以调用“DealIndex”属性更改事件)时,应用程序崩溃。

我不确定为什么会发生这种情况。有人可以阐明并提出解决方案吗?

TIA... 苏迪普

4

2 回答 2

0

你不需要开火

OnPropertyChanged("DealList");

因为该属性是 ObservableCollection。这意味着它实现了观察者模式,当添加和删除项目时,它会自行触发。

您不需要将 ObservableCollection 的绑定模式设置为 TwoWay,除非用户可以通过用户界面更新项目。您的代码似乎不允许这样做。

您也可以只在 ComboBox 上使用 SelectedIndexChanged,而不是在 CheckBox 上执行操作,除非有多个 CheckBox。这只是关于提供更好的用户体验的想法。

于 2010-04-15T14:06:35.183 回答
0

一种选择是将绑定从 selectedindex 更改为 selecteditem。你可以完成同样的事情。我最初是从尝试更改 selectedindex 开始的,但从未成功。我认为它可能是只读的。

于 2009-06-15T13:36:28.010 回答