WPF:在项目选择上关闭组合框并显示消息框

时间:2016-11-10 22:31:30

标签: c# wpf combobox

目标我在WPF中使用了Combobox,每当用户从Combobox中选择项目时,我想关闭Combobox(将旧值显示为选定值)并使用“确定/取消”按钮显示MessageBox。如果用户单击“确定”,则应设置新的选定值,否则应返回。

问题当我选择项目时,我能够显示MessageBox以及打开的Combobox,这是我不想要的。一旦用户选择了我想关闭Combobox并显示Messagebox的内容。

我怎么做?

XMAL 代码

 <ComboBox Name="Currency" Grid.Row="1" Grid.Column="5" ItemsSource="{Binding comboboxSource}"
                        SelectedValuePath="Value.bank_currency" IsReadOnly="False" IsTextSearchEnabled="True" TextSearch.TextPath="Value.bank_currency" 
                        SelectedItem="{Binding SelectedBankCurrency, UpdateSourceTrigger=LostFocus,Mode=Twoway}">

C#代码

public KeyValuePair<string, bankCurrencyObject>? SelectedBankCurrency
    {
        get { return _selectedCurrency; }
        set
        {
                MessageBoxResult result = MessageBox.Show("Are you sure you want to change the currency?",
                       "Warning",
                       MessageBoxButton.OKCancel,
                       MessageBoxImage.Question);

                if (result == MessageBoxResult.Cancel)
                {
                    return;
                }
                else
                {
                    //set values
                }
   }
   }

尝试使用selectionChanged事件,但这不起作用,

  private void Combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (DataContext == null)
            return;
        var combo = (sender as ComboBox);

        if (combo != null && combo.IsDropDownOpen)
        {
            combo.IsDropDownOpen = false;
            var binding = combo.GetBindingExpression(ComboBox.SelectedItemProperty);

            binding.UpdateSource();
            binding.UpdateTarget();
        }
    }`

2 个答案:

答案 0 :(得分:1)

您可以在SelectionChanged事件中执行此操作。

selectedItem字段会跟踪之前选择的项目,以便在没有货币更改时显示MessageBox。如果所选项目已更改,则会在显示MessageBox之前隐藏DropDown菜单。然后,如果用户单击“取消”,则会还原更改,否则会将当前选择存储在selectedItem中,以便将来进行比较。

private object selectedItem = null;

private void Currency_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (Currency.SelectedItem == selectedItem)
        return;

    Currency.IsDropDownOpen = false;

    MessageBoxResult result = MessageBox.Show("Are you sure you want to change the currency?",
           "Warning",
           MessageBoxButton.OKCancel,
           MessageBoxImage.Question);

    if (result == MessageBoxResult.Cancel)
        Currency.SelectedItem = selectedItem;
    else
        selectedItem = Currency.SelectedItem;
}

答案 1 :(得分:0)

您可以跨越.Net线程池中的任务,并通过调度程序显示消息框。