繁体   English   中英

MVVM更新组合框项目源和刷新

[英]MVVM update combobox itemsSource and refresh

我正在研究WPF项目及其MVVM。 我有一个有关刷新组合框绑定值的问题。 因此,在这种情况下,我的网格上有一个组合框和一个按钮。 我需要更改数据源,然后根据之前选择的一个步骤刷新以查看新值。

请告诉我,喜欢下一个按钮的最佳方法是什么? 之后,可能需要喜欢上一个按钮。

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>

您只是在集合中添加和删除(而不是创建一个新集合)。 这意味着您需要一个实现INotifyCollectionChanged的集合。

一个非常方便的类就是ObservableCollection<T> ,在这里,我将用它代替List<T> ,在其他任何需要更改集合以传播到UI的地方,也都可以使用。

如果您确实要进行完全刷新,则可以考虑重新创建集合,而不是执行添加/删除操作。 这可能会给您带来净的性能提升,因为每个操作都必须由UI处理,而不是一次完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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