简体   繁体   中英

combobox selection changed behaviour?

I am developing a WPF application in which i have a ComboBox ,like this

<ComboBox SelectedIndex="1" Grid.Column="2" Grid.Row="1" ItemsSource="{Binding VipCodes}" 
          SelectedItem="{Binding SelectedVipCode,Mode=OneWay}" Style="{StaticResource DefaultComboBoxStyle}" x:Name="vipCode" >
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding Description}" />
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

after loading the page when the selection changed, i need to update a value of a property.

I did like hooking up the selection changed event and set the value. But when the page loaded, the event fires and the value of a property is set.

how can i bypass this?

Just set a global variable if you absolutely have to. var SkipOnce = true; and then on page load set it to false at the end. And then in your selection changed event add: if (SkipOnce==false) { //do stuff }

Described behavior can be achieved without event handlers in code behind, by ViewModel only. If DataContext of ComboBox is set to view model, then following code will do the job:

    public MainWindowViewModel()
    {
        for (int i = 0; i < 10; i++)
        {
            _vipCodes.Add(new VipCode() { Description = i.ToString() });
        }

        SelectedVipCode = _vipCodes[3];
    }

    private ObservableCollection<VipCode> _vipCodes = new ObservableCollection<VipCode>();


    public ObservableCollection<VipCode> VipCodes
    {
        get { return _vipCodes; }
    }

    private VipCode _selectedVipCode;
    public VipCode SelectedVipCode
    {
         get { return _selectedVipCode; }
        set
        {
            _selectedVipCode = value;
            OnPropertyChanged();
        }
    }


    protected void OnPropertyChanged([CallerMemberName] string property = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM