0


WPF控件置顶及置底功能

本人通过控件的右键菜单去设置控件的置顶及置底。

以Button为例,在界面上为Button添加了右键菜单,菜单中包含了置顶与置底功能

界面:

<Grid> <Button Content="按钮" Height="80" Width="120" > <Button.ContextMenu> <ContextMenu StaysOpen="true"> <MenuItem Header="置顶" Click="MenuItem_Click"/> <MenuItem Header="置底" Click="MenuItem_Click_1"/> </ContextMenu> </Button.ContextMenu> </Button>
</Grid>

后台代码实现了置顶和置底菜单的Click事件。

代码:

///


/// 置顶
///

/// <param name="sender"></param>
/// <param name="e"></param>
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
var c = sender as Control;
var button = ContextMenuService.GetPlacementTarget(LogicalTreeHelper.GetParent(c)) as FrameworkElement;

         if (button == null) 
             return;

         Grid parent = button.Parent as Grid;
         if (parent == null) return;

         var maxZ = parent.Children.OfType<UIElement>()//linq语句,取Zindex的最大值
           .Where(x => x != button)
           .Select(x => Grid.GetZIndex(x))
           .Max();
         Grid.SetZIndex(button, maxZ + 1);
     }

    /// <summary>
     /// 置底
     /// </summary>
     /// <param name="sender"></param>
     /// <param name="e"></param>
     private void MenuItem_Click_1(object sender, RoutedEventArgs e)
     {
         var c = sender as Control;
         var button = ContextMenuService.GetPlacementTarget(LogicalTreeHelper.GetParent(c)) as FrameworkElement;

        if (button == null)
             return;

         Grid parent = button.Parent as Grid;
         if (parent == null) return;

         var minZ = parent.Children.OfType<UIElement>()//linq语句,取Zindex的最大值
           .Where(x => x != button)
           .Select(x => Grid.GetZIndex(x))
           .Min();
         Grid.SetZIndex(button, minZ - 1);
     }

其中因为所有控件继承FrameworkElement,所以对其他控件也适用。

标签: wpf c# ui

本文转载自: https://blog.csdn.net/qq_37148671/article/details/125300078
版权归原作者 无欲无求、 所有, 如有侵权,请联系我们删除。

“WPF控件置顶及置底功能”的评论:

还没有评论