如何改变图像源,而在xamarin.forms ListView中点击?
问题描述:
我有一个ListView中,我有一个图像和viewcell,什么我的要求是要改变所选行的图像内的文字,我用它acheived,
I have a ListView in which I have a image and a Text inside a viewcell, What My requirement is to change the image on selected row, I acheived it by,
var listView = new MyQuestionView(listData);
listView.ItemSelected += (sender, e) => {
listView.ItemsSource = null;
//Update the IconSource here in listData
var s = e.SelectedItem as MenuItem;
s.IconSource = "foo.png";
listView.ItemsSource = listData; //Updated List
};
不过,屏幕闪烁的第二个,同时更新这个样子。是否有更新行的元素之有道。
But, The screen flickers for a second while updating like this. Is there a proper way for updating a row's element.
这是code为我的列表视图:
public class MyQuestionView : ListView
{
public MyQuestionView (ObservableCollection<MySelectedQuestions> Qdata)
{
ObservableCollection<MySelectedQuestions> data = Qdata;
ItemsSource = data;
HasUnevenRows = true;
VerticalOptions = LayoutOptions.FillAndExpand;
BackgroundColor = Color.Transparent;
SeparatorVisibility = SeparatorVisibility.Default;
SeparatorColor = Color.FromHex("#4Dffffff");
VerticalOptions = LayoutOptions.FillAndExpand;
HorizontalOptions = LayoutOptions.FillAndExpand;
ItemTemplate = new DataTemplate (() => {
// Create views with bindings for displaying each property.
Label titleLabel = new Label ();
titleLabel.FontSize = Device.GetNamedSize(NamedSize.Medium,typeof(Label));
titleLabel.SetBinding (Label.TextProperty, "Text");
Image image = new Image ();
image.SetBinding(Image.SourceProperty, "IconSource");
return new ViewCell {
View = new StackLayout {
Padding = new Thickness (5),
Orientation = StackOrientation.Horizontal,
Children = {
image,
new StackLayout {
VerticalOptions = LayoutOptions.Center,
Spacing = 0,
Children = {
titleLabel
}
}
}
}
};
});
}
}
先谢谢了。
答
你可以使用触发器以避免闪烁做一些动画:
You could make some animations using Triggers to avoid flicker:
Image image = new Image ();
image.Triggers.Add(new Trigger(typeof(Image)) {
Property = Image.SourceProperty,
EnterActions = {
new FadeTriggerAction() {
StartsFrom = 1
}
},
ExitActions = {
new FadeTriggerAction() {
StartsFrom = 0
}
}
});
FadeTriggerAction.cs:
public class FadeTriggerAction : TriggerAction<VisualElement>
{
public FadeTriggerAction() {}
public int StartsFrom { set; get; }
protected override void Invoke (VisualElement visual)
{
visual.Animate("", new Animation( (d)=>{
var val = StartsFrom == 0 ? d : 1-d;
visual.Opacity = val;
}),
length:1000, // milliseconds
easing: Easing.Linear);
}
}