无法从视图上的视图模型绑定只读 属性 的数据

Not Able to Bind Data From Read Only Property from View Model on View

我有一个视图模型 Class 是这样设计的,我只有 getter 属性 as

  public string TPKUri
    {
        get { return localMapService.UrlMapService; }
     }

现在,您可以从下图中看到,我在 TPKUri

中得到了 UrlMapService url

但是当我试图在视图中获取 TPKUri 值时。例如,当我在 MainWindow.xaml

中尝试这样的事情时
<Grid>
<Label Content="{Binding Source={StaticResource VM}, Path=BasemapUri}" />
</Grid>

它什么都不显示。

class MainViewModel : INotifyPropertyChanged
{
    public Model myModel { get; set; }
    public LocalMapService localMapService;

    public event PropertyChangedEventHandler PropertyChanged;

    public MainViewModel()
    {
        myModel = new Model();
        CreateLocalService();
    }

    public string TPKUri
    {
        get { return localMapService.UrlMapService; }
     }

    public string MPKMap
    {
        get { return myModel.MPKPackage; }
        set
        {
            this.myModel.MPKPackage = value;
            OnPropertyChanged("MPKUri");
        }
    }
    public async void CreateLocalService()
    {
        localMapService = new LocalMapService(this.MPKMap);
        await localMapService.StartAsync();
    }


    protected void OnPropertyChanged([CallerMemberName] string member = "")
    {
        var eventHandler = PropertyChanged;
        if (eventHandler != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(member));
        }
    }
}

这是完整的MainWindow.xmal

<Window x:Class="MPK.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MPK.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
        <Window.Resources>
            <local:MainViewModel x:Key="VM"/>
        </Window.Resources>
    <Grid>
        <Label Content="{Binding Source={StaticResource VM}, Path=BasemapUri}" />
             <esri:MapView x:Name="MyMapView" Grid.Row="0"  LayerLoaded="MyMapView_LayerLoaded" >
            <esri:Map>
            <esri:ArcGISDynamicMapServiceLayer ID="Canada"  ServiceUri="{Binding Source={StaticResource VM}, Path=TPKUri}"/>
            </esri:Map>
        </esri:MapView>

    </Grid>
</Window>

您的 localMapService.StartAsync(); 是一个异步方法,但您的所有属性都没有等待结果。因此,您的 XAML 绑定可能会在您的服务完成启动之前获取属性值。

您应该做的是在您的 `localMapService.StartAsync();

之后通知 属性 更改
public async void CreateLocalService()
{
    localMapService = new LocalMapService(this.MPKMap);
    await localMapService.StartAsync();

    // Notify that the service initialization is completed.
    OnPropertyChanged(nameof(TPKUri));
    OnPropertyChanged(nameof(MPKMap));
}