0

我试图弄清楚如何在不破坏任何 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 绑定保持不变?

4

2 回答 2

2

您可以通过调用 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");
于 2013-09-04T16:55:14.867 回答
0

如果属性返回的实例发生更改,您需要触发一个PropertyChanged事件。Collection

于 2013-09-04T16:46:59.390 回答