1

I have a ComboBox's SelectedItem property bound to an object's field. It uses TwoWay binding, which works fine in most cases; when it loads up, the dropdown's selection is set from the field's getter, and manually changing the selection calls the field's setter.

However, sometimes I want to display a confirmation dialog. If the user clicks "No", I want the value to stay the same. Here is my code:

public A Afield
{
    get { return _afield; }
    set
    {
        SetA(value);
    }
}
public void SetA(LocationConfiguration value, bool prompt = true)
{
    if (/*selection would cause irreversible changes*/)
    {
        if (prompt)
        {
            MessageBoxResult result = Microsoft.Windows.Controls.MessageBox.Show(
                    "bla bla bla",
                    "bla",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Warning);
            if (result != MessageBoxResult.Yes)
                return;
        }
        PerformIrreversibleChanges()
    }
    _afield = value;
    NotifyPropertyChanged("Afield");
}

Everything in the codebehind works perfectly. If the user accepts, the changes are made. If the user presses "No", _afield is not modified. Other controls bound to this property show the correct value.

However, the ComboBox display does NOT revert to the value of _afield. It stays as whatever they selected, even if they rejected the change. For some reason it seems like it doesn't set the item of the combobox until after the property is set. At that point it displays what the user selected, not the correct value that persists in the codebehind.

4

4 回答 4

0

我设法修复它,但解决方案并不漂亮。除了绑定之外,我现在还有一个用于 SelectionChanged 事件的处理程序,它将选择更改回它应有的状态。这是代码:

private void cbox_Abox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (ComboBoxItem cbi in cbox_Abox.Items)
        if ((string)cbi.Content == BoundObject.Afield.ToString())
            cbox_Abox.SelectedItem = cbi;
}

现在,每当我手动选择 ComboBox 值时,它都会通过绑定将值写入对象(就像之前所做的那样),然后使用此处理程序将值从对象复制回 ComboBox。

出于某种原因,在此处使用 PropertyChanged 事件不会更新组合框,这就是我必须显式调用 ComboBox.SelectedIndex 的原因。

于 2012-10-04T19:59:59.743 回答
0

您需要重新设置它,因为双向绑定,您的属性将在选择更改后立即更新,因此如果用户取消更改,您需要将其重置为上一个值。您可以查看事件 args 的 RemovedItems 属性以获取先前的值。

于 2012-10-04T19:33:32.960 回答
0

或者,如果用户按下“否​​”,您可以保存以前的值并将其保留为备用

 private A previousAfield;
 public A Afield
 {
    get { return _afield; }
    set
    {
       previousAfield = _afield;
       SetA(value);
    }
 }
于 2012-10-04T20:11:57.840 回答
0

让 SetA 返回一个布尔值

set
{
     if (value == _afield) return;         
     if (SetA(value)) _afield = value;
     NotifyPropertyChanged("Afield");
}
于 2012-10-04T20:08:09.697 回答