您必须实施INotifyPropertyChanged
,然后更改才会在 UI 中更新。
这是我对您的代码所做的修改。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Molecule _CurrentMolecule;
public Molecule CurrentMolecule
{
get
{
return _CurrentMolecule;
}
set
{
_CurrentMolecule = value;
OnPropertyChanged("CurrentMolecule");
Formulas = new ObservableCollection<string>(CurrentMolecule.FormulasList.ToList());
}
}
private ObservableCollection<string> _Formulas;
public ObservableCollection<string> Formulas
{
get { return _Formulas; }
set
{
_Formulas = value;
OnPropertyChanged("Formulas");
}
}
public MainWindow()
{
InitializeComponent();
CurrentMolecule = new Molecule();
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
编辑:更好的方法是创建一个 ViewModel,然后将其绑定到Window
.
定义一个新类ViewModel
,如下所示。请注意,您可能想要更改命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace WpfApplication1
{
public class ViewModel : INotifyPropertyChanged
{
#region Properties
private Molecule _CurrentMolecule;
public Molecule CurrentMolecule
{
get
{
return _CurrentMolecule;
}
set
{
_CurrentMolecule = value;
OnPropertyChanged("CurrentMolecule");
Formulas = new ObservableCollection<string>(CurrentMolecule.FormulasList.ToList());
}
}
private ObservableCollection<string> _Formulas;
public ObservableCollection<string> Formulas
{
get { return _Formulas; }
set
{
_Formulas = value;
OnPropertyChanged("Formulas");
}
}
#endregion
#region Constructor
public ViewModel()
{
CurrentMolecule = new Molecule();
}
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
修改MainWindow
文件后面的代码如下
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}