You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin中CollectionView选中项变更时ToolbarItem文本不自动刷新

解决Xamarin.Forms中ToolbarItem绑定不刷新的问题

问题核心原因

切换CollectionView选中项时,绑定AktuellesProjekt.Name的ToolbarItem文本未刷新,主要有两个关键问题:

  1. AktuellesProjekt属性的setter未更新私有字段:原代码仅触发了PropertyChanged事件,但没有把新值赋值给_aktuellesProjekt,导致属性始终保留初始空对象。
  2. CollectionView的SelectedItem绑定模式未设置双向:默认绑定模式为OneWay,选中项变更时无法同步更新ViewModel中的属性值。

具体修复步骤

1. 修正ViewModel中AktuellesProjekt属性的setter

补充私有字段赋值逻辑,确保属性值正确更新并触发通知:

public ProjektModel AktuellesProjekt
{
    get { return _aktuellesProjekt; }
    set
    {
        if (value == _aktuellesProjekt)
            return;

        _aktuellesProjekt = value; // 新增:更新私有字段
        OnPropertyChanged(nameof(AktuellesProjekt));
    }
}

2. 修改CollectionView的SelectedItem绑定模式

在XAML中给SelectedItem绑定添加Mode=TwoWay,确保选中项变更同步到ViewModel:

<dxcv:DXCollectionView ItemsSource="{Binding Projekte}"
                       SelectedItem="{Binding AktuellesProjekt, Mode=TwoWay}"
                       SelectionMode="Single">

3. 可选:确保ProjektModel实现INotifyPropertyChanged

如果后续需要单个ProjektModel对象内部属性变更时也触发刷新,需要给模型类添加接口实现:

public class ProjektModel : INotifyPropertyChanged
{
    private int _name;
    public int Name
    {
        get => _name;
        set
        {
            if (_name != value)
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }

    // 其他属性(BestandGesamt、LetzteAktualisierung等)同理实现

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

4. 验证BaseViewModel的接口实现

确保BaseViewModel正确实现INotifyPropertyChanged,示例如下:

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

测试验证

修改完成后重新运行项目,切换CollectionView的选中项:

  • ViewModel中的AktuellesProjekt会被正确赋值并触发PropertyChanged事件
  • ToolbarItem的文本会自动更新为选中项的Name值

内容的提问来源于stack exchange,提问作者Felix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:52:48