.net 在ViewModel类中绑定静态类

0s7z1bwu  于 2023-03-09  发布在  .NET
关注(0)|答案(1)|浏览(176)

我正在玩dotnet Maui的新Map控件。一个简单的例子是让XAML像这样:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:maps="clr-namespace:Microsoft.Maui.Controls.Maps;assembly=Microsoft.Maui.Controls.Maps"
             x:Class="SaRM.MainPage">

   <maps:Map x:Name="map" MapType="Street"/>

</ContentPage>

这样我就可以访问cs文件后面的代码中的“map”:

public partial class MainPage : ContentPage
{    
    public MainPage()
    {
        InitializeComponent();  
    }

    protected override void OnAppearing()
    {
        var location = new Location(36.96, -122.0194);
        var mapSpan = new MapSpan(location, 0.01, 0.01);
        map.MoveToRegion(mapSpan);
    }
}

我希望有一个ViewModel来与XAML交互,但如果我创建一个ViewModel类如下:

public class MainViewModel
{

    public Map map;

    public MainViewModel()
    {
        var location = new Location(36.96, -122.0194);
        var mapSpan = new MapSpan(location, 0.01, 0.01);
        map.MoveToRegion(mapSpan);
    }

}

我在“Map”上看到一个错误:

"Cannot declare variable of static type 'Map'"

这是因为Map是一个静态类,在这种情况下,我怎么才能有一个绑定到XAML中Map元素的ViewModel类呢?
更新:以下是Microsoft.Maui.Maps中的Map类定义:

but5z9lq

but5z9lq1#

UI元素和UI元素类型不应该在您的ViewModel中直接引用,正如FreakyAli所说。
因为Map是一个UI元素,所以我们不能直接在ViewModel中使用它。
您可以在YourPage.xaml中定义Map,并在ViewModel上添加其他必要的数据。
例如:
可以在YourPage.xaml中添加Map,在视图模型中添加Positions

<maps:Map x:Name="map"
                  MapClicked="OnMapClicked"
                  ItemsSource="{Binding Positions}">
           
            <maps:Map.ItemTemplate>
                <DataTemplate>
                    <maps:Pin Location="{Binding Location}"
                              Address="{Binding Address}"
                              Label="{Binding Description}" />
                </DataTemplate>    
            </maps:Map.ItemTemplate>
        </maps:Map>

并将map.MoveToRegion添加到YourPage.xaml.cs

public partial class PinItemsSourcePage : ContentPage
{
    public PinItemsSourcePage()
    {
        InitializeComponent();
        BindingContext = new PinItemsSourcePageViewModel();
        map.MoveToRegion(MapSpan.FromCenterAndRadius(new Location(39.8283459, -98.5794797), Distance.FromMiles(1500)));
    }

    void OnMapClicked(object sender, MapClickedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine($"MapClick: {e.Location.Latitude}, {e.Location.Longitude}");
    }
}

并定义viewModel,如下所示:

public class PinItemsSourcePageViewModel
{
    int _pinCreatedCount = 0;
    readonly ObservableCollection<Position> _positions;

    public IEnumerable Positions => _positions;

    public ICommand AddLocationCommand { get; }
    public ICommand RemoveLocationCommand { get; }
    public ICommand ClearLocationsCommand { get; }
    public ICommand UpdateLocationsCommand { get; }
    public ICommand ReplaceLocationCommand { get; }

    public PinItemsSourcePageViewModel()
    {
        _positions = new ObservableCollection<Position>()
        {
            new Position("New York, USA", "The City That Never Sleeps", new Location(40.67, -73.94)),
            new Position("Los Angeles, USA", "City of Angels", new Location(34.11, -118.41)),
            new Position("San Francisco, USA", "Bay City", new Location(37.77, -122.45))
        };

        AddLocationCommand = new Command(AddLocation);
        RemoveLocationCommand = new Command(RemoveLocation);
        ClearLocationsCommand = new Command(() => _positions.Clear());
        UpdateLocationsCommand = new Command(UpdateLocations);
        ReplaceLocationCommand = new Command(ReplaceLocation);
    }

    void AddLocation()
    {
        _positions.Add(NewPosition());
    }

    void RemoveLocation()
    {
        if (_positions.Any())
        {
            _positions.Remove(_positions.First());
        }
    }

    void UpdateLocations()
    {
        if (!_positions.Any())
        {
            return;
        }

        double lastLatitude = _positions.Last().Location.Latitude;
        foreach (Position position in Positions)
        {
            position.Location = new Location(lastLatitude, position.Location.Longitude);
        }
    }

    void ReplaceLocation()
    {
        if (!_positions.Any())
        {
            return;
        }

        _positions[_positions.Count - 1] = NewPosition();
    }

    Position NewPosition()
    {
        _pinCreatedCount++;
        return new Position(
            $"Pin {_pinCreatedCount}",
            $"Desc {_pinCreatedCount}",
            RandomPosition.Next(new Location(39.8283459, -98.5794797), 8, 19));
    }
}

有关详细信息,您可以查看文档:Map .
以上代码来自官方样例WorkingWithMaps,请注意PinItemsSourcePage.xamlPinItemsSourcePageViewModel.cs

相关问题