none
无法在SelectionChanged事件中修改ComboBox.Text? RRS feed

  • 问题

  • <ComboBox x:Name="Key" IsEditable="True" Grid.Column="1" Grid.Row="0"/>

    Private Sub Key_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles Key.SelectionChanged
    	If Key.SelectedIndex >= 0 Then
    		Key.Text = "Value"
    	End If
    End Sub
    实验发现,在ComboBox选项修改时的确执行了该方法,修改了Text属性,但是方法结束以后Text又自动还原为了空字符串,这是咋回事?
    2021年7月22日 6:09

全部回复


  • 我不太确定需要发生什么,如果你是想要在ComboBox选择选项后显示一个默认值,你可以参考以下代码

    MainWindow.xaml代码如下:

    <Window.Resources>   
    <local:Datas x:Key="myData"/>
    </Window.Resources>
    <StackPanel>     
    <ComboBox Name="Key"SelectionChanged="SelectionChanged"   IsEditable="True"
        IsReadOnly="True"   Width="200" Height="30"
     ItemsSource="{Binding Source={StaticResource myData}}"  >      
    </ComboBox>
    </StackPanel>

     MainWindow.xaml.cs代码如下:

    public partial class MainWindow : Window   {    public MainWindow(     {   InitializeComponent();     }     private void SelectionChanged(object sender, SelectionChangedEventArgs e)     {       if (Key.SelectedIndex >= 0)       {   Action a = () => this.Key.Text = " Value";

     Dispatcher.BeginInvoke(a);       }     }   }   public class Datas:ObservableCollection<Data>   {     public Datas()     {       Add(new Data(){ Name="Data1"});       Add(new Data(){ Name="Data2"});       Add(new Data(){ Name="Data3"});     }   }   public class Data :INotifyPropertyChanged   {     private string name;     public string Name     {       get { return name; }       set       {   name = value;       OnPropertyChanged("Name");       }     }     public override string ToString()     {       return Name;     }     public event PropertyChangedEventHandler PropertyChanged;     internal void OnPropertyChanged(string prop)     {       if(this.PropertyChanged != null)       {       this.PropertyChanged(this, new PropertyChangedEventArgs(prop));       }     }   }

    结果如图:

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    <audio controls="controls" style="display:none;"></audio>

    <audio controls="controls" style="display:none;"></audio>
    2021年7月27日 9:46
  • 所以关键是修改Text属性必须要用Dipatcher是吗?

    我印象里是后台异步线程修改界面才需要用Dispatcher,这里控件本身触发的事件为啥也要Dispatcher …

    2021年8月10日 7:20