在Avalonia中,如何在鼠标悬停在椭圆和文本块上时让它们的颜色发生变化?

编程语言 2026-07-09

我在使用Avalonia开发一个Windows应用程序,到了一个需要实现的阶段:当鼠标悬停在像按钮这样的控件上时,想要改变文本颜色。我在axaml中尝试了以下代码,以在鼠标悬停在控件上时切换颜色:

<StackPanel Background="Maroon">
    <Grid Background="Transparent">
        <Border CornerRadius="5">
            <Border.Styles>
                <Style Selector="Border:pointerover">
                    <Setter Property="Background" Value="#3399FF"/>
                </Style>
            </Border.Styles>

            <Button Classes="ContentBtn" BorderBrush="Transparent" HorizontalAlignment="Stretch" CornerRadius="0" Command="{Binding ServiceConfigCommand}">
                <Button.Styles>
                    <Style Selector="Button Ellipse.indicator">
                        <Setter Property="Fill" Value="Black"/>
                    </Style>

                    <Style Selector="Button TextBlock.indicatorTxt">
                        <Setter Property="Foreground" Value="Black"/>
                    </Style>

                    <Style Selector="Button:pointerover Ellipse.indicator">
                        <Setter Property="Fill" Value="White"/>
                    </Style>

                    <Style Selector="Button:pointerover TextBlock.indicatorTxt">
                        <Setter Property="Foreground" Value="White"/>
                    </Style>
                </Button.Styles>

                <Grid ColumnDefinitions="Auto,*" ColumnSpacing="6">
                    <Ellipse Classes="indicator" Width="10" Height="10" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    <TextBlock Classes="indicatorTxt" Grid.Column="1" Text="Service Log Configuration" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="13" FontWeight="Bold"/>
                </Grid>
            </Button>

        </Border>
    </Grid>
</StackPanel>

然而,我没能让它工作。我到底哪里出错了?

解决方案

<Button.Styles>
    <Style Selector="^ Ellipse.indicator">
        <Setter Property="Fill" Value="Black"/>
    </Style>

    <Style Selector="^ TextBlock.indicatorTxt">
        <Setter Property="Foreground" Value="Black"/>
    </Style>

    <Style Selector="^:pointerover Ellipse.indicator">
        <Setter Property="Fill" Value="White"/>
    </Style>

    <Style Selector="^:pointerover TextBlock.indicatorTxt">
        <Setter Property="Foreground" Value="White"/>
    </Style>
</Button.Styles>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章