如何通知完全依赖于ObservableCollection的绑定属性的更改?

时间:2013-03-31 23:44:15

标签: c# windows-phone-7 binding asynchronous

我在类Foo上有一个绑定属性,其定义类似于以下内容(为清晰起见而编辑),

public class Foo : INotifyPropertyChanged
{
    public Foo()
    {
        // This should notify when IsHidden changes?
        MyApp.ViewModel.HiddenCategories.CollectionChanged += (s, e) => {
            this.NotifyPropertyChanged("IsHidden");
        };
    }

    public CategoryId Category { get; set; }

    // IsHidden depends on a `global' ObservableCollection object on the ViewModel
    public bool IsHidden 
    {
        get { return MyApp.ViewModel.HiddenCategories.Contains(this.Category); }
    }
    // IsHidden is toggled by adjusting the global ObservableCollection - how to notify the UI? 
    public void ToggleHidden()
    {
        if (this.IsHidden)
            MyApp.ViewModel.HiddenCategories.Remove(this.Category);
        else
            MyApp.ViewModel.HiddenCategories.Add(this.Category);
    }

    #region INotifyPropertyChanged members
    ...

}

ViewModel上定义了以下内容,

public class FooRegion
{
    public string RegionName { get; set; }
    // Foos is bound in the top ListBox DataTemplate 
    // Each Foo has properties bound in the sub ListBox DataTemplate
    public ObservableCollection<Foo> Foos { get; set; }
}

// This is actually what is bound to the top level ListBox
public ObservableCollection<FooRegion> FoosByRegion { get; set; }

public ObservableCollection<CategoryId> HiddenCategories { get; set; }

我的XAML在资源中定义了两个ItemTemplates,如下所示,

<phone:PhoneApplicationPage.Resources>
...
<DataTemplate x:Key="MainItemTemplate">
    <StackPanel >
        <TextBlock Text="{Binding Name}"/>
        <ListBox ItemsSource="{Binding Foos}"  
            ItemTemplate="{StaticResource SubItemTemplate}" />
    </StackPanel>
</DataTemplate>
... 
<DataTemplate x:Key="SubItemTemplate">
    <StackPanel  Opacity="{Binding IsHidden, Converter={StaticResource BoolToOpacity}}" >
        <toolkit:ContextMenuService.ContextMenu>
            <toolkit:ContextMenu>
                <toolkit:MenuItem Header="{Binding IsHidden, ConverterParameter=unhide foo|hide foo, 
                    Converter={StaticResource BoolToStrings}}" Tap="toggleHideFooContextMenuItem_Tap" />
            </toolkit:ContextMenu>
        </toolkit:ContextMenuService.ContextMenu>
        <TextBlock Text="Some Text Here"/>
    </StackPanel>
</DataTemplate>
...
</phone:PhoneApplicationPage.Resources>

这些资源被调用到'嵌套'ListBox,如下所示,

<ListBox ItemTemplate="{StaticResource MainItemTemplate}" ItemsSource="{Binding FoosByRegion}" />

此方法似乎只是零碎地工作,一些Foo对象在UI中更新,但其他对象则没有 - 好像通知没有到达UI。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

来自Windows Phone Toolkit的

ContextMenu应用影响周围元素不透明度的动画。将不透明度单独应用于子元素可以解决问题。