wpf 通过左右2个子按钮切换主按钮上的隐藏和可见按钮

2admgd59  于 2023-05-08  发布在  其他
关注(0)|答案(1)|浏览(162)

大家早上好,今天我想知道我如何切换主按钮显示左和右在2个二级按钮:我有三个按钮:主按钮在中间,左按钮和副按钮在两侧,左和右,当用户单击左或右时,主按钮处于隐藏属性中,然后按钮将显示,反之亦然,我的最大主按钮为7:PLAY、LEAVE、INSTALL、MAPS、INSTALL_BLOCK、RUN、REPAIR。,谢谢

private void LEFT_MouseDown(object sender, MouseButtonEventArgs e)
{
      Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate
      {
           // EXAMPLE CODE //
      }
}
private void RIGHT_MouseDown(object sender, MouseButtonEventArgs e)
{
      Dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate
      {
           // EXAMPLE CODE //
      }
}
vlju58qv

vlju58qv1#

最好的方法是使用集合管理按钮。将所有按钮放入一个容器中,如Grid,并命名该容器。

<DockPanel HorizontalAlignment="Center"
            VerticalAlignment="Center">
    <Button Width="40"
            Height="40"
            VerticalAlignment="Bottom"
            Click="LeftButton_Click"
            Content="l"
            DockPanel.Dock="Left" />
    <Button Width="40"
            Height="40"
            VerticalAlignment="Bottom"
            Click="RightButton_Click"
            Content="r"
            DockPanel.Dock="Right" />
    <Grid x:Name="ButtonContainer"
            Width="100"
            Height="100">
        <Button Content="1" />
        <Button Content="2" />
        <Button Content="3" />
        <Button Content="4" />
    </Grid>
</DockPanel>

在后面的代码中,我们可以查询命名容器中所有Button类型的子元素,并将它们存储到列表中。

public partial class MainWindow : Window
{
    private readonly List<Button> _buttons;
    private int _activeButtonIndex = 0;

    public MainWindow( MainWindowViewModel viewModel )
    {
        InitializeComponent();

        _buttons = ButtonContainer.Children.OfType<Button>().ToList();
        _buttons.ForEach( b => b.Visibility = Visibility.Hidden );
        _buttons[_activeButtonIndex].Visibility = Visibility.Visible;
    }
}

现在,很容易遍历按钮列表,隐藏旧按钮并使新按钮可见。

private void LeftButton_Click( object sender, RoutedEventArgs e )
    {
        _buttons[_activeButtonIndex].Visibility = Visibility.Hidden;
        if ( ++_activeButtonIndex >= _buttons.Count ) _activeButtonIndex = 0;
        _buttons[_activeButtonIndex].Visibility = Visibility.Visible;
    }

    private void RightButton_Click( object sender, RoutedEventArgs e )
    {
        _buttons[_activeButtonIndex].Visibility = Visibility.Hidden;
        if ( --_activeButtonIndex < 0 ) _activeButtonIndex = _buttons.Count - 1;
        _buttons[_activeButtonIndex].Visibility = Visibility.Visible;
    }

相关问题