You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中如何实现图片默认隐藏、点击按钮后显示?

.NET MAUI 图片默认隐藏、点击按钮显示并启用其他按钮的正确实现

问题原因

你用IsEnabled控制图片显示是错误的——IsEnabled属性仅用于控制控件是否能响应用户交互(比如点击、触摸),不会影响控件的可见性,所以图片会一直显示。

正确实现方法:使用IsVisible属性

要控制图片的显示/隐藏,应该使用IsVisible属性,默认设置为False隐藏图片,点击按钮后设置为True显示。

修改后的XAML代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="AppMaui.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Padding="30,0"
            Spacing="25">
            <!-- 默认设置IsVisible="False"隐藏图片 -->
            <Image
                x:Name="CounterImage"
                Source="dotnet_bot.png"
                HeightRequest="185"
                Aspect="AspectFit"
                SemanticProperties.Description="dot net bot in a race car number eight"
                IsVisible="False" />

            <Label
                Text="Hello, World!"
                Style="{StaticResource Headline}"
                SemanticProperties.HeadingLevel="Level1" />

            <Label
                Text="Welcome to &#10;.NET Multi-platform App UI"
                Style="{StaticResource SubHeadline}"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I" />

            <Button
                x:Name="CounterBtn"
                Text="Click me" 
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                IsEnabled="False"
                HorizontalOptions="Fill" />

            <Button
                x:Name="MakePictureButton"
                Text="Make counter" 
                SemanticProperties.Hint="button make picture of counter"
                Clicked="OnMakePictureClicked"
                HorizontalOptions="Fill" />
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

修改后的C#代码

namespace AppMaui
{
    public partial class MainPage : ContentPage
    {
        int count = 0;

        public MainPage()
        {
            InitializeComponent();
        }

        private void OnCounterClicked(object sender, EventArgs e)
        {
            count++;

            CounterBtn.Text = count == 1 ? $"Clicked {count} time" : $"Clicked {count} times";

            SemanticScreenReader.Announce(CounterBtn.Text);
        }

        private void OnMakePictureClicked(object sender, EventArgs e)
        {
            if (count == 0)
            {
                CounterImage.IsVisible = true; // 改为设置IsVisible属性
                CounterBtn.IsEnabled = true;
                MakePictureButton.IsEnabled = false;
            }
        }
    }
}

其他可行方案

1. MVVM数据绑定(推荐用于复杂场景)

如果项目后续会扩展功能,推荐使用MVVM模式,通过数据绑定控制控件状态,避免直接操作UI控件:

  • 新建ViewModel类,实现INotifyPropertyChanged接口:
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using Microsoft.Maui.Controls;
    
    namespace AppMaui
    {
        public class MainViewModel : INotifyPropertyChanged
        {
            private bool _isImageVisible;
            private bool _isCounterBtnEnabled;
            private int _count;
    
            public bool IsImageVisible
            {
                get => _isImageVisible;
                set { _isImageVisible = value; OnPropertyChanged(); }
            }
    
            public bool IsCounterBtnEnabled
            {
                get => _isCounterBtnEnabled;
                set { _isCounterBtnEnabled = value; OnPropertyChanged(); }
            }
    
            public ICommand MakePictureCommand { get; }
            public ICommand CounterCommand { get; }
    
            public MainViewModel()
            {
                IsImageVisible = false;
                IsCounterBtnEnabled = false;
                MakePictureCommand = new Command(ExecuteMakePicture);
                CounterCommand = new Command(ExecuteCounter);
            }
    
            private void ExecuteMakePicture()
            {
                if (_count == 0)
                {
                    IsImageVisible = true;
                    IsCounterBtnEnabled = true;
                }
            }
    
            private void ExecuteCounter()
            {
                _count++;
                // 可在此处理按钮文本更新逻辑,或新增属性绑定文本
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            private void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    
  • 在XAML中绑定属性和命令:
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:AppMaui"
                 x:Class="AppMaui.MainPage">
        <ContentPage.BindingContext>
            <local:MainViewModel />
        </ContentPage.BindingContext>
    
        <ScrollView>
            <VerticalStackLayout
                Padding="30,0"
                Spacing="25">
                <Image
                    Source="dotnet_bot.png"
                    HeightRequest="185"
                    Aspect="AspectFit"
                    SemanticProperties.Description="dot net bot in a race car number eight"
                    IsVisible="{Binding IsImageVisible}" />
    
                <Label
                    Text="Hello, World!"
                    Style="{StaticResource Headline}"
                    SemanticProperties.HeadingLevel="Level1" />
    
                <Label
                    Text="Welcome to &#10;.NET Multi-platform App UI"
                    Style="{StaticResource SubHeadline}"
                    SemanticProperties.HeadingLevel="Level2"
                    SemanticProperties.Description="Welcome to dot net Multi platform App U I" />
    
                <Button
                    Text="Click me" 
                    SemanticProperties.Hint="Counts the number of times you click"
                    Command="{Binding CounterCommand}"
                    IsEnabled="{Binding IsCounterBtnEnabled}"
                    HorizontalOptions="Fill" />
    
                <Button
                    Text="Make counter" 
                    SemanticProperties.Hint="button make picture of counter"
                    Command="{Binding MakePictureCommand}"
                    HorizontalOptions="Fill" />
            </VerticalStackLayout>
        </ScrollView>
    </ContentPage>
    

2. 动态添加/移除控件

默认不将Image加入布局,点击按钮时再插入到VerticalStackLayout中:

private void OnMakePictureClicked(object sender, EventArgs e)
{
    if (count == 0 && !VerticalStackLayout.Children.Contains(CounterImage))
    {
        VerticalStackLayout.Children.Insert(0, CounterImage); // 插入到布局首位
        CounterBtn.IsEnabled = true;
        MakePictureButton.IsEnabled = false;
    }
}

这种方法适合不需要频繁切换显示状态的场景,缺点是频繁操作控件集合可能影响性能。

内容的提问来源于stack exchange,提问作者kkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 20:17:02