我试图弄清楚如何在不破坏任何 XAML 绑定的情况下创建对象的新实例。现在我正在使用的只是一个ObservableCollection
我会调用的:
Container.MyClass.MyCollection
在我的 ViewModel 中(通过 Kind of Magic 实现 INPC):
public ObservableCollection<MyObject> Collection
{
get { return Container.MyClass.MyCollection; }
}
在我看来:
<StackPanel>
<TextBlock Text="{Binding Collection.Count}" />
<ItemsControl ItemsSource="{Binding Collection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
因此,如果我尝试获取班级的“新鲜”实例,我可以调用它并使绑定保持不变:
public void WorkingSomewhatFreshInstance()
{
Container.MyClass.MyCollection.Clear();
Container.MyClass.MyCollection.Add(new MyObject() { Name = "Test1" });
Container.MyClass.MyCollection.Add(new MyObject() { Name = "Test2" });
}
但是,如果我调用此方法:
public MyClass BrokenFreshInstance()
{
var myClass = new MyClass();
myClass.MyCollection.Add(new MyObject() { Name = "Test1" });
myClass.MyCollection.Add(new MyObject() { Name = "Test2" });
return myClass;
}
接着:
Container.MyClass = Initialize.BrokenFreshInstance();
绑定不再更新。有什么方法可以使用对象的新实例并使 XAML 绑定保持不变?