WPF MeasureOverride和 ArrangeOverride做個 頁面導航
阿新 • • 發佈:2018-12-12
public class NavigationPanel:Panel { protected override Size MeasureOverride(Size availableSize) { Size size = new Size(); for (int i = 0; i < this.InternalChildren.Count; i++) { var child = this.InternalChildren[i]; child.Measure(availableSize); size= child.DesiredSize; } return base.MeasureOverride(size); } protected override Size ArrangeOverride(Size finalSize) { var thisWidth = finalSize.Width; for (int i = 0; i < this.InternalChildren.Count; i++) {var child = this.InternalChildren[i]; var poingX = thisWidth - child.DesiredSize.Width; if (poingX > 0) { child.Arrange(new Rect(new Point(poingX, 0), child.DesiredSize)); } else { child.Arrange(new Rect(new Point(0, 0), child.DesiredSize)); } } return base.ArrangeOverride(finalSize); } }
<local:NavigationPanel x:Name="_navigationpanel_" Width="60" MaxWidth="300" Background="Yellow" HorizontalAlignment="Left"> <Button BorderBrush="Black" Background="Red" Content="0" Width="40" Margin="10" Click="Button_Click"></Button> </local:NavigationPanel>
private void Button_Click(object sender, RoutedEventArgs e) { if (_navigationpanel_.Width == 300) _navigationpanel_.Width = 60; else _navigationpanel_.Width = 300; }
當然這只是個半成品,還可以向NavigationPanel中加入子控制元件來做一個完整的導航。
用MeasureOverride和 ArrangeOverride做導航最大的好處是:
1、在控制元件的最上層
2、可以隨著窗體大小來調整Height
導航實現方式有很多,這個純粹是為了MeasureOverride和 ArrangeOverride 練手。