【问题标题】:WP7: Binding to an element outside pivot.itemtemplateWP7:绑定到 pivot.itemtemplate 之外的元素
【发布时间】:2011-03-21 17:23:21
【问题描述】:

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

我正在将枢轴绑定到要显示的对象集合以创建画廊。这是我绑定到一个名为 gallery 的列表的枢轴控件,其中每个对象包含 2 个字符串(url 和描述)。

<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 是视图模型,并在页面的构造函数中初始化。 这是我的视图模型:

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 超出范围,我尝试按照here. 的说明设置 ElementName

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

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

【问题讨论】:

    标签: windows-phone-7 binding scope pivot


    【解决方案1】:

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

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

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

    【讨论】:

    • 我想我会使用代理方法,因为属性 ShowDetail 是一个共享属性(静态)。感谢您如此快速清晰地回答!
    猜你喜欢
    • 2012-01-06
    • 2010-12-02
    • 2018-01-21
    • 1970-01-01
    • 2011-05-09
    • 2011-10-17
    • 2012-04-28
    • 2014-01-07
    • 1970-01-01
    相关资源
    最近更新 更多