在 Xamarin 應用程式中,我試圖將 textcolor 與 Message 模型中的屬性系結。
public class Message : INotifyPropertyChanged
{
public string text { get; set; }
public Color color { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
任務是,當我單擊 collectionview 中的標簽時,文本應更改為灰色。
我可以更改 ObservableCollection 中的顏色: this.messages = new ObservableCollection(); (這是有效的,如果我洗掉 ObservableCollection 中的條目,螢屏會更新)
但是當我更改訊息模型中的顏色時,螢屏不會更新。
我使用 MVVMhelpers,如果可能的話,我想用它來解決問題。
此致..
uj5u.com熱心網友回復:
當您單擊專案以觸發 的SelectionChanged事件時,您可以將專案顏色更改為灰色CollectionView。
Xml:
<CollectionView ItemsSource="{Binding messages}" SelectionMode="Single" SelectionChanged="CollectionView_SelectionChanged">
<CollectionView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding text}" TextColor="{Binding color}"></Label>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
后面的代碼:
public partial class Page2 : ContentPage
{
public ObservableCollection<Message> messages { get; set; }
public Page2()
{
InitializeComponent();
messages = new ObservableCollection<Message>()
{
new Message(){ text="A", color="Red"},
new Message(){ text="B", color="Red"},
new Message(){ text="C", color="Red"},
};
this.BindingContext = this;
}
private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var previousItem = e.PreviousSelection.FirstOrDefault() as Message;
var currentItem = e.CurrentSelection.FirstOrDefault() as Message;
currentItem.color = "Gray";
if (previousItem!=null)
{
previousItem.color = "Red";
}
}
}
public class Message : INotifyPropertyChanged
{
private string _text;
public string text
{
get
{
return _text;
}
set
{
_text = value;
OnPropertyChanged("text");
}
}
private string _color;
public string color
{
get
{
return _color;
}
set
{
_color = value;
OnPropertyChanged("color");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
uj5u.com熱心網友回復:
超級,非常感謝。
我還應該補充
<DataTemplate x:DataType="{x:Type Models:Message}">
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371239.html
