我是 WPF 新手,当某些属性发生变化时,我无法让我的网格自动刷新。我实现的唯一一件事 - 添加元素时自动刷新。
这是我的代码:
public partial class MainWindow : Window
{
private Model model;
public MainWindow()
{
InitializeComponent();
model = new Model();
MyGrid.ItemsSource = model.Content;
}
private void MyButton_Click(object sender, RoutedEventArgs e)
{
MyGrid.Items.Refresh();
}
}
public class Model
{
public ObservableCollection<Single> Content;
private Random r;
private Action action;
private static object _syncLock = new object();
public Model()
{
Content = new ObservableCollection<Single>();
r = new Random();
action = new Action(process);
action.BeginInvoke(null,null);
BindingOperations.EnableCollectionSynchronization(Content, _syncLock);
}
private void process()
{
while (true)
{
Content.Add(new Single { Name = "name" });
Content[r.Next(0,Content.Count())].Name = "rename" + r.Next(1,100);
Thread.Sleep(1000);
}
}
}
public class Single : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
RaisePropertyChanged(Name);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}