绑定到对象的新实例

本文关键字:实例 新实例 对象 绑定 | 更新日期: 2023-09-27 18:30:14

我正试图弄清楚如何在不破坏任何XAML绑定的情况下创建对象的新实例。现在我所使用的只是一个ObservableCollection,我称之为:

Container.MyClass.MyCollection

在我的ViewModel中(通过某种魔术实现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绑定不变吗?

绑定到对象的新实例

您可以通过调用Observable:上的PropertyChanged来告诉View刷新与新实例的绑定

public ObservableCollection<MyObject> Collection
{
    get { return _collection; }
    set 
    {
        _collection = value;
        RaisePropertyChangedEvent("Collection");
    }
}

您需要将集合分配给此属性以触发事件:

 Collection = Container.MyClass.MyCollection;   //This will trigger the PropertyChangedEvent
 ...
 Container.MyClass = Initialize.BrokenFreshInstance();
 Collection = Container.MyClass.MyCollection;   // Trigger again..

或者,您可以通过以下操作手动提出更改:

Container.MyClass = Initialize.BrokenFreshInstance();
RaisePropertyChangedEvent("Collection");
如果属性返回的实例发生更改,则需要为Collection激发PropertyChanged事件。