繁体   English   中英

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

[英]WP7: Binding to an element outside pivot.itemtemplate

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

我正在将透视图绑定到要显示的对象集合上,以创建画廊。 这是绑定到名为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>

数据上下文是视图模型,并在页面的构造函数中初始化。 这是我的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));
    }
}

画廊对象是我的ViewModel中的列表,作为ShowDetail属性。 由于ShowDetail不在范围内,因此我尝试按照此处说明的那样设置ElementName

枢轴与画廊列表绑定良好,但是当我更改ShowDetail的值时,网格将不会隐藏。 我也尝试将ElementName设置为LayoutRoot,但仍然无法正常工作。

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

DataTemplateElementName绑定仅引用该DataTemplate的元素名称。 数据模板中的数据上下文是Gallery实例,而不是GalleryViewModel 您可以将ShowDetail属性向下移动到Gallery类。

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

如果您不熟悉此代理概念,那么Dan Wahlin在该主题上的帖子应该会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM