這可以通過訂閱兩個元素的SizeChanged
事件輕鬆完成,並在每次調用處理程序時更新GridView
的Height
。
但您想要一個純粹的XAML解決方案,並且這就是Behaviors發揮作用的地方。
使用行爲。
首先,您需要爲您的項目添加Blend SDK參考。
然後,您需要創建一個新類,實現IBehavior
。本課程僅需要參考GridView
,item
和itemTitle
三個dependency properties
。所以你可以訂閱他們的SizeChanged
事件並相應地調用Height
。
我選擇這個行爲附加到頂級Panel
(最有可能您LayoutRootGrid
),因爲我想確保下所有元素及其Loaded
事件處理中正確地呈現。
的完全行爲類會是這個樣子 -
public class HeightBehavior : DependencyObject, IBehavior
{
public GridView GridView
{
get { return (GridView)GetValue(GridViewProperty); }
set { SetValue(GridViewProperty, value); }
}
public static readonly DependencyProperty GridViewProperty =
DependencyProperty.Register("GridView", typeof(GridView), typeof(HeightBehavior), new PropertyMetadata(null));
public FrameworkElement FirstItem
{
get { return (FrameworkElement)GetValue(FirstItemProperty); }
set { SetValue(FirstItemProperty, value); }
}
public static readonly DependencyProperty FirstItemProperty =
DependencyProperty.Register("FirstItem", typeof(FrameworkElement), typeof(HeightBehavior), new PropertyMetadata(null));
public FrameworkElement SecondItem
{
get { return (FrameworkElement)GetValue(SecondItemProperty); }
set { SetValue(SecondItemProperty, value); }
}
public static readonly DependencyProperty SecondItemProperty =
DependencyProperty.Register("SecondItem", typeof(FrameworkElement), typeof(HeightBehavior), new PropertyMetadata(null));
public DependencyObject AssociatedObject { get; set; }
public void Attach(DependencyObject associatedObject)
{
this.AssociatedObject = associatedObject;
var control = (Panel)this.AssociatedObject;
control.Loaded += AssociatedObject_Loaded;
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
this.FirstItem.SizeChanged += FirstItem_SizeChanged;
this.SecondItem.SizeChanged += SecondItem_SizeChanged;
// force to re-calculate the Height
this.FirstItem.Width += 0.5;
}
private void FirstItem_SizeChanged(object sender, SizeChangedEventArgs e)
{
this.SetAssociatedObjectsHeight();
}
private void SecondItem_SizeChanged(object sender, SizeChangedEventArgs e)
{
this.SetAssociatedObjectsHeight();
}
private void SetAssociatedObjectsHeight()
{
this.GridView.Height = this.FirstItem.ActualHeight - this.SecondItem.ActualHeight;
}
public void Detach()
{
this.FirstItem.SizeChanged -= FirstItem_SizeChanged;
this.SecondItem.SizeChanged -= SecondItem_SizeChanged;
var control = (Panel)this.AssociatedObject;
control.Loaded -= AssociatedObject_Loaded;
}
}
然後在我的XAML,我把它連接到我的頂級Grid
,像這樣。
<Grid x:Name="LayoutRoot">
<Interactivity:Interaction.Behaviors>
<local:HeightBehavior GridView="{Binding ElementName=itemGridView}" FirstItem="{Binding ElementName=item}" SecondItem="{Binding ElementName=itemTitle}"/>
</Interactivity:Interaction.Behaviors>
希望這會有所幫助。
+1行爲SDK –