Xamarin表单:根据字符串值隐藏和显示listview项

时间:2018-04-11 07:49:55

标签: listview xamarin.forms xamarin.ios

我有一个如下图所示的列表视图。还有一个图标(蓝色),并在每个列表项的右侧切换。

enter image description here

我有一个名为type的字符串变量,如果“type”值为“switch”,我需要隐藏列表中的更多图标并仅显示开关图标,如果“type”值为“more”隐藏列表中的开关并仅显示更多图标。

more和switch在listview里面如下:

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.View>
                    <StackLayout>
                        //Items like profile image name 
                        <Image   //more icon     />
                        <Switch/>
                    </StackLayout>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

提前致谢

2 个答案:

答案 0 :(得分:0)

您可以尝试创建转换器:

public class StringToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((string)value == "switch")
        {
            if ((string)parameter == "Image") return false;

            return true;
        }
        if ((string)parameter == "Image") return true;
        return false;
    }

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

然后在页面xaml中使用它:

<ContentPage.Resources>
    <ResourceDictionary>
        <local:StringToBoolConverter x:Key="stringToBool" />
    </ResourceDictionary>
</ContentPage.Resources>
<StackLayout>
    <ListView x:Name="MyListView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.View>
                        <StackLayout Orientation="Horizontal">
                            <Image IsVisible="{Binding Path=type, Converter={StaticResource stringToBool}, ConverterParameter=Image}" />
                            <Switch IsVisible="{Binding Path=type, Converter={StaticResource stringToBool}, ConverterParameter=Switch}"/>
                        </StackLayout>
                    </ViewCell.View>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

将字符串转换为bool,并使用参数告诉转换器应隐藏哪个控件。

答案 1 :(得分:-1)

你可以创建一个转换器(如提到的Land Lu),或者你可以为每个转换器创建一个属性。如果你只是为了几件物品而去做,那么一个物业就足够了。如果你有很多,那么使用转换器可能是一种更好的方法。

在此页面的BindingContext(应该是ViewModel)中,添加两个新属性:

public bool CanShowSwitch => type == "switch";
public bool CanShowMore => type == "more";

“type”是同一个类中的公共字符串属性。现在只需更新你的xaml即可添加IsVisible属性:

<Image IsVisible="{Binding CanShowMore}" />
<Switch IsVisible="{Binding CanShowSwitch}"/>

或者,如果只有两个项目,并且你想显示/或,你可能只有一个属性并使用反布尔转换器,但那时,你正在使用一个转换器,也可能去与其他转换器方法。这三种方法都是解决同一问题的不同方法。

相关问题