【问题标题】:BInding textColor in Xamarin在 Xamarin 中绑定 textColor
【发布时间】:2022-01-04 01:23:50
【问题描述】:

在 Xamarin 应用程序中,我尝试将 textcolor 与消息模型中的属性绑定。

public class Message : INotifyPropertyChanged
{
    public string text { get; set; }
    public Color color { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
}

任务是,当我单击集合视图中的标签时,文本应变为灰色。

我可以更改 ObservableCollection 中的颜色: this.messages = new ObservableCollection(); (这是可行的,如果我删除 ObservableCollection 中的条目,屏幕会更新)

但是当我在消息模型中更改颜色时,屏幕没有更新。

我使用 MVVMhelpers,如果可能的话,我想用它来解决问题。

最好的问候..

【问题讨论】:

  • set for color 不会调用 PropertyChanged,因此 UI 不会收到属性已更新的通知

标签: xamarin binding


【解决方案1】:

您可以在单击项目时将项目颜色更改为灰色以触发CollectionViewSelectionChanged 事件。

Xaml:

   <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));
    }
}

【讨论】:

    【解决方案2】:

    太好了,非常感谢。

    我也应该补充

    <DataTemplate x:DataType="{x:Type Models:Message}">
    

    【讨论】:

    • x:DataType 不是必需的。很高兴您解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多