在Xamarin Forms中的按钮上有条件地设置图像

时间:2018-08-31 14:26:50

标签: c# xamarin xamarin.forms

是否有可能在动态填充的ListView中的Xamarin Forms中的按钮上有条件地显示图像?

例如,总而言之,如果条件在后面的代码中为true,则我需要用红色填充一颗心形按钮,否则不是红色。

public func tuple(seq:[String], value:String, block:(String) -> ()) {
    if seq.count > 0 {
        for i in 0..<seq.count {
            var uu = seq;
            let kk:String = uu[i];
            uu.remove(at: i)
            self.tuple(seq:uu,value: value + kk, block: block)
        }
    } else {
        block(value)
    }
}

最初构建页面时,我将遍历列表。如果名称在列表中,则需要将图像更改为<ListView x:Name="FullNamesList" VerticalOptions="FillAndExpand" ItemSelected="FullNamesList_OnItemSelected"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="1.1*" /> <ColumnDefinition Width=".3*" /> </Grid.ColumnDefinitions> <Label FontSize="Medium" FontAttributes="Bold" HorizontalTextAlignment="Start" Margin="20,0,0,0" VerticalTextAlignment="Center" Grid.Row="0" Grid.Column="0"> <Label.Triggers> <DataTrigger TargetType="Label" Binding="{Binding Gender}" Value="F"> <Setter Property="Text" Value="{Binding Name}" /> <Setter Property="TextColor" Value="#cc0066" /> </DataTrigger> <DataTrigger TargetType="Label" Binding="{Binding Gender}" Value="M"> <Setter Property="Text" Value="{Binding Name}" /> <Setter Property="TextColor" Value="#007acc" /> </DataTrigger> <DataTrigger TargetType="Label" Binding="{Binding Gender}" Value="A"> <Setter Property="Text" Value="{Binding Name}" /> <Setter Property="TextColor" Value="#00994d" /> </DataTrigger> </Label.Triggers> </Label> <Label Text="{Binding ShortMeaning}" FontSize="Small" TextColor="Gray" VerticalTextAlignment="Center" Grid.Row="0" Grid.Column="1" /> <Button Image="favorite.png" Grid.Row="0" Grid.Column="2" Scale=".9" Opacity=".3" ClassId="{Binding Name}" Clicked="FavoriteHeart_OnClicked" x:Name="favoriteHeart"> </Button> </Grid> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>

1 个答案:

答案 0 :(得分:1)

您需要替换assert才能进行绑定。

Button Image="Favorite.png"

然后在您的ViewModel中的某个位置:

声明一个<Button Image="{Binding FavoriteImage}" Grid.Row="0" Grid.Column="2" Scale=".9" Opacity=".3" ClassId="{Binding Name}" Clicked="FavoriteHeart_OnClicked" x:Name="favoriteHeart"> 绑定,然后为该变量设置一个值

FavoriteImage