如何更新 DataTemplate 中的绑定?

How to update bindings inside DataTemplate?

假设我有以下 ListView

<ListView x:Name="ListView1" ItemsSource="{Binding SomeCollection}">
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Do something" Command="{Binding SomeCommand, Mode=OneWay}" />
        </ContextMenu>
    </ListView.ContextMenu>
    <ListView.ItemTemplate>
        <DataTemplate DataType="model:Person">
            <StackLayout>
                <TextBlock Text="{Binding Name}">
                <Image Source="{Binding State, Converter={StaticResource StateToIconConverter}, Mode=OneWay}" />
            </StackLayout>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

现在,这个 Person 是一个模型,它的属性没有任何方式通知视图它们正在更新(根据 MVVC)。但是,我需要在 SomeCommand 执行后更新视图,因为 SomeCollection 中的项目被编辑了。

我试过这样做

public void ExecuteSomeCommand() {
    // change the state of some person inside SomeCollection
    (ListView1.SelectedItems[0] as Person).State = "Some different state";

    // now inform the view of change, so it can reflect in the DataTemplate
    ListView1.GetBindingExpression(ListBox.ItemsSourceProperty).UpdateTarget();
}

我认为这会传播到 DataTemplate,但事实并非如此。还有其他方法吗?我应该如何改变我的方法?

当数据绑定中使用的模型实现 INotifyPropertyChanged Interface 时,当您修改模型的 属性 时,UI 会自动更新。

public class Person : INotifyPropertyChanged
{
    private Image _state;
    public Image State
    {
        get => _state;
        set {
            if (value != _state) {
                _state = value;
                OnPropertyChanged(nameof(State));
            }
        }
    }

    // ... other properties here ...

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}