首页 文章

更改Xamarin Forms XAML按钮的isVisible属性

提问于
浏览
6

我想在Xamarin Forms ContentPage中动态显示/隐藏按钮 . 我的XAML代码中有两个按钮:

<StackLayout Orientation="Vertical">

    <Button x:Name="start_btn" Clicked="startPanic">
        <Button.Text>START</Button.Text>
    </Button>

    <Button x:Name="stop_btn" IsVisible="false">
        <Button.Text>STOP</Button.Text>
    </Button>

</StackLayout>

对应的C#代码:

public partial class PanicPage : ContentPage
{
    private Button startBtn;
    private Button stopBtn;

    public PanicPage ()
    {
        InitializeComponent ();
        startBtn = this.FindByName<Button> ("start_btn");
        stopBtn = this.FindByName<Button> ("stop_btn");
    }

    private void startPanic(object sender, EventArgs args){
        Device.BeginInvokeOnMainThread (() => {
            startBtn.IsVisible = false;
            stopBtn.IsVisible = true; //  DOESN'T WORK, button still will be hidden
        });
    }
}

当我在XAML中设置isVisible属性时,它不会对事件方法(startPanic)中的任何属性更改做出反应 . 我该如何解决?

4 回答

  • 1

    在xmal文件中更改代码并写入启动和停止按钮的属性

    <Button x:Name="start_btn" Clicked="startPanic" IsVisible="{Binding IsStartVisible}">
        <Button.Text>START</Button.Text>
    </Button>
    
    <Button x:Name="stop_btn" IsVisible="{Binding IsStopVisible}">
        <Button.Text>STOP</Button.Text>
    </Button>
    

    在ViewModel中为开始按钮编写以下属性和类似属性,并根据您的逻辑设置IsStopVisible = true / false

    私人布尔_isStopVisible;

    public bool IsStopVisible{
            get {
                return _isStopVisible;
            }
            set {
                _isStopVisible= value;
                RaisePropertyChanged ("IsStopVisible");
            }
        }
    
  • 9

    它应该工作得很好 . 我复制了你的代码并将其清理了一下,它显示了STOP按钮,然后是我

    几点评论:

    • 尽可能使用短的属性 <Button Text="X"/> ,它更容易阅读

    • 当你添加一个XAML页面时,IDE会在它旁边添加一个.xaml.cs文件并生成另一个.g.cs,你不要为它们定义占位符,也不需要按名称找到它们

    • 所有UI启动的事件都在UI线程上执行,无需明确地执行此操作

    这是XAML,与你的相同,只是更紧凑并添加了边距,因此按钮可见

    <StackLayout Orientation="Vertical" Margin="20">
      <Button x:Name="start_btn" Clicked="startPanic" Text="START" />
      <Button x:Name="stop_btn" Text="STOP" IsVisible="false" />
    </StackLayout>
    

    而背后的代码:

    public partial class TestPage : ContentPage
    {   
        public TestPage ()
        {
            InitializeComponent ();
        }
    
        private void startPanic(object sender, EventArgs args){
            Device.BeginInvokeOnMainThread (() => {
                start_btn.IsVisible = false;
                stop_btn.IsVisible = true;  
            });
        }
    }
    
  • 0

    也许我迟到但我也在搜索这个也没有成功 . 这可能对某人有用 .

    objectView.SetValue(IsVisibleProperty, false); // the view is GONE, not invisible
    objectView.SetValue(IsVisibleProperty, true);
    
  • 1

    使用视图的Visibility属性 .

    例如,如果你想让你的按钮不可见,你就可以做到

    if(condition)
    
        {
    
        button.Visibility=ViewStates.Invisible;
    
        }
    
        else
    
        {
    
        button.Visibility=ViewStates.Visible;
    
        }
    

相关问题