【发布时间】:2016-12-31 10:17:38
【问题描述】:
我正在制作词汇应用程序并尝试在我的 Xamarin.Forms 列表视图中实现最喜欢的单词。
请看下面的截图
现在我使用硬代码而不是 MVVM 这是我的模型
namespace Mamtil.Models
{
public class Word
{
public int Id { get; set; }
public string word { get; set; }
public string translation { get; set; }
public string audio { get; set; }
public bool favorite { get; set; }
public string groupBy => translation[0].ToString().ToUpper();
}
}
XAML
...
<ViewCell>
<StackLayout Orientation="Horizontal">
<Button x:Name="FavoriteButton" Image="gray_star.png" BackgroundColor="#F5F5F5" Clicked="Favorite" BorderRadius="0" WidthRequest="45" CommandParameter="{Binding .}" />
<Switch IsToggled="{Binding favorite}" WidthRequest="50"/>
<StackLayout Orientation="Vertical" HorizontalOptions="FillAndExpand" Margin="5, 0, 0, 0">
<Label Text="{Binding translation}">
<Label.FontSize>
<OnPlatform x:TypeArguments="x:Double" iOS="11" Android="18" />
</Label.FontSize>
</Label>
<Label Text="{Binding word}" TextColor="#1565C0">
<Label.FontSize>
<OnPlatform x:TypeArguments="x:Double" iOS="11" Android="13" />
</Label.FontSize>
</Label>
</StackLayout>
<Button x:Name="SpeechButton" Image="ic_mic_black_24dp.png" BackgroundColor="#F5F5F5" Clicked="GoToSpeach" BorderRadius="0" WidthRequest="45" CommandParameter="{Binding Id}" />
</StackLayout>
</ViewCell>
所以问题是当我从数据库加载数据时,我如何初始化 FavoriteButton 的图像,如
<!-- Here switch is toggled or not depending on Binding value. I want to do something like this but with image of Button -->
<Switch IsToggled="{Binding favorite}">
在上面的代码中,它是硬编码的,但我想根据 Word.favorite 值进行更改。在运行时,我设法像这样更改图像
async void Favorite(object sender, EventArgs e)
{
var b = (Button)sender;
Word t = (Word)b.CommandParameter;
//update in database
await App.MamtilRepo.UpdateFavoriteAsync(t.Id);
if (t.favorite)
b.Image = "gray_star.png";
else
b.Image = "yellow_star.png";
t.favorite = !t.favorite;
}
举个例子:
...
// Some thing like
if(Word.favorite)
Image = yellow_star.png;
else
Image = gray_star.png;
我应该在代码中还是在 XAML 中做一些事情
我希望能清楚地描述我的问题。提前致谢
【问题讨论】:
标签: xamarin.forms