简体   繁体   中英

MVVM update combobox itemsSource and refresh

I'm working on a WPF project and its MVVM. I got a problem about refreshing combobox binding value. So, here its the case, i have a combobox and button on my grid. I need to change datasource then refresh to see new values according to selected one step before.

Please tell me what is the best method to like next button? After that maybe need to like previous button.

public MyScriptForm(IMyScriptModel viewModel) {
  this.Model=viewModel;
  InitializeComponent();
  Height=Double.NaN;
  Width=Double.NaN;
}
public IMyScriptModel Model {
  get {
    return this.DataContext as IMyScriptModel;
  }
  set {
    this.DataContext=value;
  }
}
private void btnNext_Click(object sender,
RoutedEventArgs e) {
  /// to what ?
  Model.cbxAnswer.Clear();
  Model.cbxAnswer.add("Step2Data");
}
Create{//its a huge project, this working on when this form created
  myScript.Model.cbxAnswer.Add("1");
  myScript.Model.cbxAnswer.Add("2");
  myScript.Model.cbxAnswer.Add("3");
  }
destroy{}

////////////////////////
//Onmy model 
public List<string> cbxAnswer {
  get {
    return m_cbxAnswer;
  }
  set {
    m_cbxAnswer=value;
    OnPropertyChanged("cbxAnswer");
  }
}
public List<string> m_cbxAnswer=new List<string>();
 public event PropertyChangedEventHandler PropertyChanged;
 protected void OnPropertyChanged(string propertyName) {
  if (PropertyChanged !=null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

XAML:

<Grid>
  <ComboBox Name="cbxAnswer" HorizontalAlignment="Left" Margin="10,130,0,0" VerticalAlignment="Top" Width="130" Height="25" ItemsSource="{Binding Path=cbxAnswer}" />
  <Button Name="btnNext" HorizontalAlignment="Left" Margin="215,130,0,0" VerticalAlignment="Top" Width="75" Content="İlerle" Click="btnNext_Click" />

</Grid>

You are just adding and removing from the collection (as opposed to creating a new one). This means that you need a collection that implements INotifyCollectionChanged .

A very convenient class that already does this is ObservableCollection<T> , which I would use instead of List<T> here, and anywhere else you need collection changes to propagate to the UI.

If you are truly doing a full refresh, you may consider just recreating the collection instead of doing add/removes. This could give you a net performance gain, as doing each operation individually must be handled by the UI, as opposed to all at once.

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