WP7:绑定到pivot.itemtemplate外的元素

时间:2011-03-21 17:23:21

标签: windows-phone-7 binding scope pivot

我已经在这方面苦苦挣扎了一段时间。我是一个新手,但我潜伏了很多,仍然找不到我的问题的解决方案,所以我决定在这里发布我的问题。

我将一个数据透镜绑定到我想要显示的对象集合以创建一个库。这是我的枢轴控件绑定到名为gallery的列表,其中每个对象包含2个字符串(url和description)。

<controls:Pivot ItemsSource="{Binding gallery}" Grid.Row="0" x:Name="galleryPivot">
            <controls:Pivot.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                            </Grid.RowDefinitions>
                            <Image Source="{Binding url}" />
                            <Grid Visibility="{Binding ElementName=galleryPivot, Path=DataContext.ShowDetail}">
                                <ListBox>
                                    <ListBoxItem>
                                        <StackPanel>
                                            <TextBlock Text="{Binding description}" />
                                        </StackPanel>
                                    </ListBoxItem>
                                </ListBox>
                            </Grid>
                        </Grid>
                    </StackPanel>
                </DataTemplate>
            </controls:Pivot.ItemTemplate>
        </controls:Pivot>

datacontext是viewmodel并在页面的构造函数中初始化。 这是我的ViewModel:

public class GalleryViewModel : INotifyPropertyChanged
{
    public List<Gallery> gallery
    {
        get { return Globals.pictures; }

    }

    private Visibility _showDetail = Visibility.Collapsed;
    public Visibility ShowDetail
    {
        get { return _showDetail; }
        set {
           _showDetail = value;
           RaisePropertyChanged("ShowDetail");
        }
    }       
    public GalleryViewModel()
    { }

    public event PropertyChangedEventHandler PropertyChanged = delegate { return; };
    protected void RaisePropertyChanged(string propertyName)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

gallery对象是我的ViewModel中的列表,作为ShowDetail属性。由于ShowDetail不在范围内,我尝试按照here.

的说明设置ElementName

枢轴与图库列表绑定良好,但是当我更改ShowDetail的值时,网格将不会隐藏。我也尝试将ElementName设置为LayoutRoot,但它仍然不起作用。

我的问题是,当它超出itemtemplate的范围时,如何绑定可见性?

1 个答案:

答案 0 :(得分:3)

DataTemplate内, ElementName 绑定仅指代DataTemplate内的元素的名称。数据模板中的数据上下文是Gallery实例,而不是GalleryViewModel。您可以将 ShowDetail 属性转移到Gallery类。

如果您不想这样做,那么另一种方法是使用数据上下文的代理,您将其作为资源添加到页面并绑定到页面的数据上下文(GalleryViewModel实例想必)。然后,您可以像访问父数据上下文的任何其他资源一样引用该资源。

如果您不熟悉此代理概念,那么Dan Wahlin's post on the subject应该会有所帮助。