gpt4 book ai didi

c# - 如何使按钮以编程方式在 Windows Phone 中可见?

转载 作者:行者123 更新时间:2023-11-30 13:37:59 24 4
gpt4 key购买 nike

我有一个名为删除 的按钮。我只想在满足某些条件时才可见,那我该怎么做呢??

创建按钮的 XAML 代码是

<Button x:Name="DeleteButton" Content="Delete" HorizontalAlignment="Left" Height="64" Margin="74,579,0,-9" VerticalAlignment="Top" Width="314" FontSize="24"/>

最佳答案

你有一个 Visibility 属性。

你有一些方法可以做到:

  1. 就在后面的代码中,您应该:

    if (condition)
    {
    DeleteButton.Visibility = Visibility.Visible; //Also possible to Collapse (hide).
    }

    上面的代码应该可以帮助您分别使按钮不可见和可见。

    注意:这是不太可取的,它不是动态的,会导致重复和不必要的代码。

  2. 更好和更动态的方法是:

    您可以创建一个 bool 属性并将可见性按钮绑定(bind)到它,如下所示:

    bool IsVisible { get; set; } //Code behind

    在 xaml 中:

    <!-- Pay attention: The Converter is still not written, follow next steps -->
    <Button x:Name="DeleteButton"
    Content="Delete"
    HorizontalAlignment="Left" Height="64" Margin="74,579,0,-9"
    VerticalAlignment="Top" Width="314" FontSize="24"
    Visibility="{Binding IsVisible,
    Converter={StaticResource BooleanToVisibilityConverter}}" />

    转换器:

    public class BooleanToVisibilityConverter : IValueConverter
    {
    /// <summary>
    /// Converts a value.
    /// </summary>
    /// <param name="value">The value produced by the binding source.</param>
    /// <param name="targetType">The type of the binding target property.</param>
    /// <param name="parameter">The converter parameter to use.</param>
    /// <param name="culture">The culture to use in the converter.</param>
    /// <returns>A converted value. Returns Visible if the value is true; otherwise, collapsed.</returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
    return (bool)value ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter,CultureInfo culture)
    {
    throw new NotImplementedException();
    }
    }

    并且在 xaml 中的资源中,您应该添加转换器,以便您可以使用 StaticResource 访问它:

    <Application
    x:Class="UI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:converters="using:UI.Converters">

    <converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />

    然后根据需要更改 IsVisible 属性,如果为 true,它将绑定(bind)到 Visible,如果为 false,它将被折叠。

    if (condition)
    {
    IsVisible = true;
    }

    更多信息你应该学习:binding , converters .

关于c# - 如何使按钮以编程方式在 Windows Phone 中可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19582801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com