[英]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范圍時,如何綁定可見性?
在DataTemplate
, ElementName綁定僅引用該DataTemplate
的元素名稱。 數據模板中的數據上下文是Gallery
實例,而不是GalleryViewModel
。 您可以將ShowDetail屬性向下移動到Gallery
類。
如果您不想這樣做,那么另一種選擇是對數據上下文使用代理,將其作為資源添加到頁面並綁定到頁面的數據上下文(大概是GalleryViewModel
實例)。 然后,您可以像在父數據上下文中獲取任何其他資源一樣引用該資源。
如果您不熟悉此代理概念,那么Dan Wahlin在該主題上的帖子應該會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.