如何更改listview selected / ItemTapped项文本颜色Xamarin.forms。
以下是我的代码
namespace StoreProject.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SelectFilters : ContentPage
{
public ObservableCollection<Item> Items { get; set; } = new ObservableCollection<Item>();
public SelectFilters()
{
InitializeComponent();
BindingContext = this;
Items.Add(new Item { Name = "GENDER" });
Items.Add(new Item { Name = "SIZE" });
Items.Add(new Item { Name = "STYLE" });
Items.Add(new Item { Name = "BRAND" });
Items.Add(new Item { Name = "PRICE" });
Items.Add(new Item { Name = "COLOR" });
}
private void lstView_ItemSelected(object sender, ItemTappedEventArgs e)
{
try
{
// string itm = e.SelectedItem.ToString();
var dataItem = e.Item as Item;
dataItem.TextColor = Color.Red;
dataItem.OnPropertyChanged();
// update listView
dataItem.OnPropertyChanged();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
public class Item : INotifyPropertyChanged
{
public string Name { get; set; }
public Color TextColor { get; set; } = Color.Black;
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(""));
}
}
}
答案 0 :(得分:1)
您必须为ListView
ItemsSource
的视图模型设置颜色属性。实施INotifyPropertyChanged
,以便在更改列表视图的内容时更新ListView
:
public class ItemViewModel : INotifyPropertyChanged
{
...
public string Name { get; set; } = "";
public Color TextColor { get; set; } = Color.Black;
// event handler for updating the list views
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(""));
}
}
然后向您的ItemsSource
添加一个事件监听器和ListView
:
listView.ItemTapped += Tapped;
var itemsSource = new ObservableCollection<ItemViewModel>{
new ItemViewModel { Name = "aaa" },
new ItemViewModel { Name = "bbb" },
new ItemViewModel { Name = "ccc" },
new ItemViewModel { Name = "ddd" },
new ItemViewModel { Name = "eee" },
new ItemViewModel { Name = "fff" },
};
listView.ItemsSource = itemsSource;
并设置所选项目的文字颜色:
void Tapped(object sender, ItemTappedEventArgs args)
{
var listView = sender as ListView;
var selectedItem = args.Item as ItemViewModel;
// set the text color of the selected item
foreach (ItemViewModel item in listView.ItemsSource) {
// set the text color
// reset text color if the items are not selected
item.TextColor = selectedItem.Equals(item) ? Color.Green : Color.Black;
// update listView
item.OnPropertyChanged();
}
}
XAML中的ListView
Binding
字段为TextColor
:
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<AbsoluteLayout>
<Label Text="{Binding Name}"
TextColor="{Binding TextColor}"
AbsoluteLayout.LayoutFlags="All"
AbsoluteLayout.LayoutBounds="0.5, 0.5, 0.9, 0.9"/>
</AbsoluteLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>