无法绑定View模型上View模型的只读属性中的数据

时间:2018-12-06 23:12:56

标签: c# wpf mvvm model-view

我有一个像这样设计的视图模型类,并且我有一个只有吸气剂的属性

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

现在您可以从下图看到,我在UrlMapService中获得了TPKUri网址

enter image description here

但是当我试图在视图中获取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>

1 个答案:

答案 0 :(得分:1)

您的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));
}
相关问题