![](/img/trans.png)
[英]How to refresh combobox after changing selection in another combobox in WPF
[英]WPF, how to reset combobox after selection is made
我想在每次選擇后將組合框重置為默認文本值。 這個問題在這里問得很好,但那個解決方案對我根本不起作用。 對我來說確實有意義的解決方案是將 SelectedIndex 設置為 -1 並重置 Text ,如下所示
主窗口.xaml
<ComboBox Name="combobox" SelectionChanged="ComboBox_SelectionChanged" IsEditable="True" IsReadOnly="True" Text="My Default Text">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Background" Value="Blue"/>
<Setter Property="BorderBrush" Value="Blue"/>
<Setter Property="BorderThickness" Value="0"/>
</Style>
</ComboBox.ItemContainerStyle>
<ComboBoxItem Name="selection0">selection0</ComboBoxItem>
<ComboBoxItem Name="selection1">selection1</ComboBoxItem>
<ComboBoxItem Name="selection2">selection2</ComboBoxItem>
<ComboBoxItem Name="selection3">selection3</ComboBoxItem>
<ComboBoxItem Name="selection4">selection4</ComboBoxItem>
</ComboBox>
主窗口.xaml.cs
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string name = selectedItem.Name;
if (selectedItem != null)
{
MessageBox.Show(string.Format(string));
//This does set the combobox to empty, but no text is added.
this.combobox.SelectedIndex = -1;
this.combobox.Text = "My Default Text";
}
}
SelectedIndex 確實成功轉到 -1,但它保持為空。 我希望文本回到它最初所說的內容,但我沒有運氣。 任何幫助表示贊賞。
獲得所選項目后,您可以將ComboBox
重置回其默認狀態,但您必須在單獨的Dispatcher
消息中執行此操作:
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.combobox.SelectedItem != null)
{
MessageBox.Show(this.combobox.SelectedItem.ToString());
}
Action a = () => this.combobox.Text = "My Default Text";
Dispatcher.BeginInvoke(a);
}
如果您嘗試在同一條消息中執行此操作,那么您的更改將有效地被 WPF 的內部邏輯取代,該內部邏輯在您的事件處理程序完成后運行。
我在后面的代碼中使用 DropDownOpened 事件來在每次打開 ComboBox 時重置它。
public partial class ChangeArticleAndSoftwareBundleRevisionDialog : UserControl
{
public Dialog()
{
InitializeComponent();
ComboBox.DropDownOpened += ComboBox_DropDownOpened;
}
private void ComboBox_DropDownOpened(object sender, System.EventArgs e)
{
ComboBox combobox = (sender as ComboBox);
combobox.SelectedIndex = 0;
combobox.SelectedValue = null;
combobox.SelectedItem = null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.