目标 我在 WPF 中有组合框,每当用户从组合框中选择项目时,我想关闭组合框(将旧值显示为所选值)并显示带有确定/取消按钮的消息框。如果用户单击“确定”,则应设置新选定的值,否则应返回。
问题当我选择项目时,我可以显示消息框并打开组合框,但我不希望这样做。一旦用户选择某些内容,我想关闭组合框并显示消息框。
我该怎么做?
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();
}
}`
最佳答案
您可以在 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;
}
关于c# - WPF : Close combobox on item selection and display Message box,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40538175/