【问题标题】:Set IsVisible property by a string value of model通过模型的字符串值设置 IsVisible 属性
【发布时间】:2019-03-12 20:21:31
【问题描述】:

我正在使用 XAML 定义一个 ListView,每个单元格都有多个按钮。 我想根据字符串值是否为空来触发可见性。 我在 ListView 中的按钮是:

<Button Text="{Binding Phone}" 
        Clicked="OnPhoneClicked"
        CommandParameter="{Binding Telefono}"
        x:Name="btnPhone" />

绑定Phone 是从我的模型中读取的。它正确显示。

如果Phone 的值为空字符串,如何设置IsVisible 属性按钮?

【问题讨论】:

    标签: xaml xamarin xamarin.forms xamarin.forms.listview


    【解决方案1】:

    试试这个代码

    <Button Text="{Binding Phone}" 
        Clicked="OnPhoneClicked"
        CommandParameter="{Binding Telefono}"
        x:Name="btnPhone"
        IsVisible="{Binding Phone,Converter={StaticResource StringNullOrEmptyBoolConverter"} />
    

    StringNullOrEmptyBoolConverter.cs 文件

    public class StringNullOrEmptyBoolConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var s = value as string;
            return !string.IsNullOrWhiteSpace(s);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    最后添加到App.xaml文件中

     <Application.Resources>
            <ResourceDictionary>
                <Converter:StringNullOrEmptyBoolConverter x:Key="StringNullOrEmptyBoolConverter" />
            </ResourceDictionary>
        </Application.Resources>
    

    【讨论】:

    • 需要我创建一个新类 StringNullOrEmptyBoolConverter 并在 xaml 标头上对其进行索引吗?
    • 是的,需要在项目的某处创建新的 .cs 文件。
    • 德克萨斯州。我正在尝试您的解决方案。当我将 x:local="myproject.Utils" 放在标题上并使用 IsVisible="{Binding Mail, Converter={StaticResource StringNullOrEmptyBoolConverter} }" 时,出现错误“StaticResource not found for key StringNullOrEmptyBoolConverter”
    • @doxsi - 我已经更新了我的答案,请检查一次。将您的班级名称设为 StringNullOrEmptyBoolConverter 只是为了避免混淆。
    猜你喜欢
    • 1970-01-01
    • 2010-11-08
    • 2012-03-21
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2013-03-11
    相关资源
    最近更新 更多