xaml - Xamarin Forms 显示/隐藏条目选项

标签 xaml xamarin xamarin.forms

目前我正在研究 Xamarin.Forms,想知道是否有可能向输入字段添加显示/隐藏选项?

最佳答案

我通过在多个输入字段上方使用展开/折叠图标解决了类似的问题。

XAML 中的显示/隐藏元素

添加固定大小 (20x20) 的可点击图像,引用 PCL 中的嵌入资源:

<Image Source="{Binding ShowHideIcon, Converter={StaticResource StringToResImageSourceConverter}}" WidthRequest="20" HeightRequest="20"">
    <Image.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding ShowHideCommand}" />
    </Image.GestureRecognizers>
</Image>

ViewModel 处理命令:

每次触摸图像时切换 bool 值。

public bool EntryVisible { get; set; }

public Command ShowHideCommand{
    get {
        return new Command((object o) => {
            EntryVisible = !EntryVisible;
            if (EntryVisible) { 
                ShowHideIcon = "ic_collapse"; 
            } else { 
                ShowHideIcon = "ic_expand"; 
            }
        }
    }
}

XAML 中的标签和条目

将 Label 和 Entry 的 IsVisible 属性绑定(bind)到 ViewModel 中的 bool 值。

<Label Text="Quantity" IsVisible="{Binding EntryVisible}" />
<Entry Text="{Binding Quantity}" IsVisible="{Binding EntryVisible}" />

为了完整起见,我使用了 https://developer.xamarin.com/guides/xamarin-forms/working-with/images/#Embedded_Images在 PCL Resources 文件夹中存储图像 ic_expand.pngic_collapse.png

需要转换器来转换字符串,例如“ic_expand”为 XAML 可以使用的图像引用。

public class StringToResImageSourceConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        var resString = (string)value;
        if (!string.IsNullOrEmpty(resString)) {
            return ImageSource.FromResource("ProjectName.Resources." + resString + ".png");
        }
        return null;
    }

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

关于xaml - Xamarin Forms 显示/隐藏条目选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868787/

相关文章:

xaml - 如何在 WP7 Bing Map 控件上放置多个圆形叠加层?

c# - 如何在 UWP 后台任务中使用 XAML UI 元素?

xamarin - 关闭 Xamarin 表单 'Entry' 组件上的自动更正

c# - 防止 Xamarin Android 应用程序中的方向更改

Xamarin Forms 2.0 AppCompat android 键盘模式

c# - 当应用程序不在使用 Xamarin Crossplatform 的设备的最近历史记录中时如何显示本地通知

c# - 以 Xamarin 形式实现视频通话,我有哪些选择?

wpf - 是否可以仅使用 XAML 触发器单击按钮来永久更改图像的源?

wpf - XAML 绑定(bind)到 ViewModel 上的 CollectionViewSource 属性

android - 错误 "java.exe"以代码 1 退出 - Xamarin