【问题标题】:Xamarin Forms Bindable Object Value Changed EventXamarin Forms 可绑定对象值更改事件
【发布时间】:2020-02-28 09:57:28
【问题描述】:

我使用 Xamarin Forms Map 创建了一个自定义地图。我想在 VisibleRegion 更改时访问更新的 VisibleRegion。

自定义渲染器

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    base.OnElementPropertyChanged(sender, e);

    if (Element == null)
        return;

    var map = (CustomMap)sender;
    if(map.VisibleRegion==null)
        return;

    map.OnMapRegionUpdated();
}

在自定义控件中我创建了一个可绑定属性

public MapCenterPosition MapCenter { get; set; }
public static readonly BindableProperty MapCenterProperty = BindableProperty.Create(
            nameof(MapCenter),
            typeof(MapCenterPosition),
            typeof(CustomMap),
            null);


public void OnMapRegionUpdated()
{
   MapCenter = new MapCenterPosition {Position = VisibleRegion.Center};
}

地图中心位置.cs

public class MapCenterPosition: INotifyPropertyChanged
{
    private Position _position;

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChange([CallerMemberName]string propertyname = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }

    public Position Position
    {
        get => _position;
        set 
        { 
            _position = value;
            RaisePropertyChange();
        }

    }
}

现在我有了 CustomMap 并将其绑定到 ViewModel 代码。但是,当 MapCenter 更新时,如何在 ViewModel 中触发某些方法?

【问题讨论】:

    标签: c# xaml xamarin xamarin.forms


    【解决方案1】:

    我犯了一个简单的错误

    我所要做的就是在 xaml 中将绑定模式设置为 TwoWay。

    在自定义控件中,我应该替换这个

    public MapCenterPosition MapCenter { get; set; }
    

    public MapCenterPosition MapCenter
    {
        get => (MapCenterPosition) GetValue(MapCenterProperty);
        set => SetValue(MapCenterProperty,value);
    }
    

    现在我可以在每次 MapCenter 更新时触发视图模型中的方法。

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 2018-03-01
      • 2017-10-09
      相关资源
      最近更新 更多