微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ArcGIS API for Silverlight开发中鼠标左键点击地图上的点弹出窗口及右键点击弹出快捷菜单的实现代码

1、首先在SL项目中添加一个抽象类ContextMenu.cs文件代码如下:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;

namespace MapClient
{
    public abstract class ContextMenu
    {
        private Point _location;
        private bool _isShowing;
        private Popup _popup;
        private Grid _grid;
        private Canvas _canvas;
        private FrameworkElement _content;

        //初始化并显示弹出窗体.公共方法显示菜单项时调用
        public void Show(Point location)
        {
            if (_isShowing)
                throw new InvalidOperationException();
            _isShowing = true;
            _location = location;
            ConstructPopup();
            _popup.IsOpen = true;
        }

        //关闭弹出窗体
        public void Close()
        {
            _isShowing = false;
            if (_popup != null)
            {
                _popup.IsOpen = false;
            }
        }

        //abstract function that the child class needs to implement to return the framework element that needs to be displayed in the popup window.
        protected abstract FrameworkElement GetContent();

        //Default behavior for OnClickOutside() is to close the context menu when there is a mouse click event outside the context menu
        protected virtual void OnClickOutside()
        {
            Close();
        }

        // 用Grid来布局,初始化弹出窗体
        //在Grid里面添加一个Canvas,用来监测菜单项外面的鼠标点击事件
        //
        // Add the Framework Element returned by GetContent() to the grid and position it at _location
        private void ConstructPopup()
        {
            if (_popup != null)
                return;
            _popup = new Popup();
            _grid = new Grid();
            _popup.Child = _grid;
            _canvas = new Canvas();
            _canvas.MouseLeftButtonDown += (sender,args) => { OnClickOutside(); };
            _canvas.MouseRightButtonDown += (sender,args) => { args.Handled = true; OnClickOutside(); };
            _canvas.Background = new SolidColorBrush(Colors.Transparent);
            _grid.Children.Add(_canvas);
            _content = GetContent();
            _content.HorizontalAlignment = HorizontalAlignment.Left;
            _content.VerticalAlignment = VerticalAlignment.Top;
            _content.Margin = new Thickness(_location.X,_location.Y,0);
            _grid.Children.Add(_content);
            UpdateSize();
        }

        /// <summary>
        /// 更新大小
        /// </summary>
        private void UpdateSize()
        {
            _grid.Width = Application.Current.Host.Content.ActualWidth;
            _grid.Height = Application.Current.Host.Content.ActualHeight;
            if (_canvas != null)
            {
                _canvas.Width = _grid.Width;
                _canvas.Height = _grid.Height;
            }
        }
    }
}

2、再添加一个类用来实现左键点击弹出控件MapTips.cs文件代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using MapClient.ServiceReference1;

namespace MapClient
{
    public class MapTips : ContextMenu
    {
        RichTextBox rtb;
        string placeName = string.Empty;
        string areaID = string.Empty;
        string year = string.Empty;
        string cycleID = string.Empty;

        //弹出窗口中的显示文本控件
        TextBlock tb_title; //标题
        TextBlock tb_grade1; //苗情等级1
        TextBlock tb_grade2; //苗情等级2
        TextBlock tb_grade3; //苗情等级3
        TextBlock tb_grade4; //苗情等级4

        TextBlock tb_percent1; //占比1
        TextBlock tb_percent2; //占比2
        TextBlock tb_percent3; //占比3
        TextBlock tb_percent4; //占比4

        TextBlock tb_area1; //面积1
        TextBlock tb_area2; //面积2
        TextBlock tb_area3; //面积3
        TextBlock tb_area4; //面积4

        HyperlinkButton hlb1; //超链接1
        HyperlinkButton hlb2; //超链接2
        HyperlinkButton hlb3; //超链接3

        public MapTips(RichTextBox rtb,string name,string areaID,string year,string cycleID)
        {
            this.rtb = rtb;
            this.placeName = name;
            this.areaID = areaID;
            this.year = year;
            this.cycleID = cycleID;
        }


        //构造菜单按钮并返回一个FrameworkElement对象
        protected override FrameworkElement GetContent()
        {
            Border border = new Border() { BorderBrush = new SolidColorBrush(Color.FromArgb(255,167,171,176)),BorderThickness = new Thickness(1),Background = new SolidColorBrush(Colors.White) };
            border.Effect = new DropShadowEffect() { BlurRadius = 3,Color = Color.FromArgb(255,230,227,236) };
            Grid grid = new Grid() { Margin = new Thickness(1) };
            //九行
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            grid.RowDeFinitions.Add(new RowDeFinition() { Height = new GridLength(30) });
            //三列
            grid.ColumnDeFinitions.Add(new ColumnDeFinition() { Width = new GridLength(80) });
            grid.ColumnDeFinitions.Add(new ColumnDeFinition() { Width = new GridLength(80) });
            grid.ColumnDeFinitions.Add(new ColumnDeFinition() { Width = new GridLength(80) });
            //标题第一列
            tb_title = new TextBlock() { FontSize = 14,HorizontalAlignment = HorizontalAlignment.Center,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_title,0);
            Grid.SetColumn(tb_title,0);
            Grid.SetColumnSpan(tb_title,3);
            grid.Children.Add(tb_title);
            //苗情等级标题
            TextBlock tb_grade = new TextBlock() { Text = "苗情等级",FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_grade,1);
            Grid.SetColumn(tb_grade,0);
            grid.Children.Add(tb_grade);
            //旺苗
            tb_grade1 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_grade1,2);
            Grid.SetColumn(tb_grade1,0);
            grid.Children.Add(tb_grade1);
            //一级苗
            tb_grade2 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_grade2,3);
            Grid.SetColumn(tb_grade2,0);
            grid.Children.Add(tb_grade2);
            //二级苗
            tb_grade3 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_grade3,4);
            Grid.SetColumn(tb_grade3,0);
            grid.Children.Add(tb_grade3);
            //三级苗
            tb_grade4 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_grade4,5);
            Grid.SetColumn(tb_grade4,0);
            grid.Children.Add(tb_grade4);
            //占比标题
            TextBlock tb_percent = new TextBlock() { Text = "占   比",VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_percent,1);
            Grid.SetColumn(tb_percent,1);
            grid.Children.Add(tb_percent);
            //旺苗占比
            tb_percent1 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_percent1,2);
            Grid.SetColumn(tb_percent1,1);
            grid.Children.Add(tb_percent1);
            //一级苗占比
            tb_percent2 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_percent2,3);
            Grid.SetColumn(tb_percent2,1);
            grid.Children.Add(tb_percent2);
            //二级苗占比
            tb_percent3 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_percent3,4);
            Grid.SetColumn(tb_percent3,1);
            grid.Children.Add(tb_percent3);
            //三级苗占比
            tb_percent4 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_percent4,5);
            Grid.SetColumn(tb_percent4,1);
            grid.Children.Add(tb_percent4);
            //面积标题
            TextBlock tb_area = new TextBlock() { Text = "面积(万亩)",VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_area,1);
            Grid.SetColumn(tb_area,2);
            grid.Children.Add(tb_area);
            //旺苗面积(万亩)
            tb_area1 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_area1,2);
            Grid.SetColumn(tb_area1,2);
            grid.Children.Add(tb_area1);
            //一级苗面积(万亩)
            tb_area2 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_area2,3);
            Grid.SetColumn(tb_area2,2);
            grid.Children.Add(tb_area2);
            //二级苗面积(万亩)
            tb_area3 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_area3,4);
            Grid.SetColumn(tb_area3,2);
            grid.Children.Add(tb_area3);
            //三级苗面积(万亩)
            tb_area4 = new TextBlock() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(tb_area4,5);
            Grid.SetColumn(tb_area4,2);
            grid.Children.Add(tb_area4);

            //超链接(苗情评价分析)
            hlb1 = new HyperlinkButton() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(hlb1,6);
            Grid.SetColumn(hlb1,0);
            Grid.SetColumnSpan(hlb1,3);
            grid.Children.Add(hlb1);
            //超链接(苗情数据报表)
            hlb2 = new HyperlinkButton() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(hlb2,7);
            Grid.SetColumn(hlb2,0);
            Grid.SetColumnSpan(hlb2,3);
            grid.Children.Add(hlb2);
            //超链接(苗情监测报告)
            hlb3 = new HyperlinkButton() { FontSize = 14,VerticalAlignment = VerticalAlignment.Center };
            Grid.SetRow(hlb3,8);
            Grid.SetColumn(hlb3,0);
            Grid.SetColumnSpan(hlb3,3);
            grid.Children.Add(hlb3);



            border.Child = grid;

            getData1SoapClient client = new getData1SoapClient();
            client.GetCommentInfoCompleted += new EventHandler<GetCommentInfoCompletedEventArgs>(client_GetCommentInfoCompleted);
            client.GetCommentInfoAsync(areaID,year,cycleID);

            return border;
        }

        void client_GetCommentInfoCompleted(object sender,GetCommentInfoCompletedEventArgs e)
        {
            //设置值
            tb_title.Text = result.Split(',')[0].Split(':')[1];
            //苗情评价分析
            hlb1.Content = result.Split(',')[1].Split(':')[1];
            hlb1.NavigateUri = new Uri("http://www.baidu.com",UriKind.RelativeOrAbsolute);
            //苗情数据报表
            hlb2.Content = result.Split(',')[2].Split(':')[1];
            hlb2.NavigateUri = new Uri("http://www.baidu.com",UriKind.RelativeOrAbsolute);
            //苗情监测报告
            hlb3.Content = result.Split(',')[3].Split(':')[1];
            hlb3.NavigateUri = new Uri("http://www.baidu.com",UriKind.RelativeOrAbsolute);
            //旺苗等级、占比和面积
            tb_grade1.Text = result.Split(',')[4].Split('|')[0].Split(':')[1];
            tb_percent1.Text = result.Split(',')[4].Split('|')[1].Split(':')[1];
            tb_area1.Text = result.Split(',')[4].Split('|')[2].Split(':')[1];
            //一级苗等级、占比和面积
            tb_grade2.Text = result.Split(',')[5].Split('|')[0].Split(':')[1];
            tb_percent2.Text = result.Split(',')[5].Split('|')[1].Split(':')[1];
            tb_area2.Text = result.Split(',')[5].Split('|')[2].Split(':')[1];
            //二级苗等级、占比和面积
            tb_grade3.Text = result.Split(',')[6].Split('|')[0].Split(':')[1];
            tb_percent3.Text = result.Split(',')[6].Split('|')[1].Split(':')[1];
            tb_area3.Text = result.Split(',')[6].Split('|')[2].Split(':')[1];
            //三级苗等级、占比和面积
            tb_grade4.Text = result.Split(',')[7].Split('|')[0].Split(':')[1];
            tb_percent4.Text = result.Split(',')[7].Split('|')[1].Split(':')[1];
            tb_area4.Text = result.Split(',')[7].Split('|')[2].Split(':')[1];

        }
    }
}

3、添加一个鼠标右键弹出的快捷菜单控件RTBContextMenu .cs文件代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;

namespace MapClient
{
    public class RTBContextMenu : ContextMenu
    {
        RichTextBox rtb;
        string placeName = string.Empty;

        public RTBContextMenu(RichTextBox rtb,string name)
        {
            this.rtb = rtb;
            this.placeName = name;
        }

        //构造菜单按钮并返回一个FrameworkElement对象
        protected override FrameworkElement GetContent()
        {
            Border border = new Border() { BorderBrush = new SolidColorBrush(Color.FromArgb(255,236) };
            Grid grid = new Grid() { Margin = new Thickness(1) };
            grid.ColumnDeFinitions.Add(new ColumnDeFinition() { Width = new GridLength(25) });
            grid.ColumnDeFinitions.Add(new ColumnDeFinition() { Width = new GridLength(105) });
            grid.Children.Add(new Rectangle() { Fill = new SolidColorBrush(Color.FromArgb(255,233,238,238)) });
            grid.Children.Add(new Rectangle() { Fill = new SolidColorBrush(Color.FromArgb(255,226,228,231)),HorizontalAlignment = HorizontalAlignment.Right,Width = 1 });

            //田间视频
            Button tjspButton = new Button() { Height = 22,Margin = new Thickness(0,0),HorizontalAlignment = HorizontalAlignment.Stretch,VerticalAlignment = VerticalAlignment.Top,HorizontalContentAlignment = HorizontalAlignment.Left };
            tjspButton.Style = Application.Current.Resources["ContextMenuButton"] as Style;
            tjspButton.Click += tjsp_MouseLeftButtonUp;
            Grid.SetColumnSpan(tjspButton,2);
            StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
            Image tjspImage = new Image() { HorizontalAlignment = HorizontalAlignment.Left,Width = 16,Height = 16,Margin = new Thickness(1,0) };
            tjspImage.source = new BitmapImage(new Uri("/MapClient;component/Images/pop-movie.png",UriKind.RelativeOrAbsolute));
            sp.Children.Add(tjspImage);
            TextBlock tjspText = new TextBlock() { Text = "田间视频",HorizontalAlignment = HorizontalAlignment.Left,Margin = new Thickness(16,0) };
            sp.Children.Add(tjspText);
            tjspButton.Content = sp;
            grid.Children.Add(tjspButton);

            //作物像片
            Button zwxpButton = new Button() { Height = 22,24,HorizontalContentAlignment = HorizontalAlignment.Left };
            zwxpButton.Style = Application.Current.Resources["ContextMenuButton"] as Style;
            zwxpButton.Click += zwxp_MouseLeftButtonUp;
            Grid.SetColumnSpan(zwxpButton,2);
            sp = new StackPanel() { Orientation = Orientation.Horizontal };
            Image zwxpImage = new Image() { HorizontalAlignment = HorizontalAlignment.Left,0) };
            zwxpImage.source = new BitmapImage(new Uri("/MapClient;component/Images/pop-pic.png",UriKind.RelativeOrAbsolute));
            sp.Children.Add(zwxpImage);
            TextBlock zwxpText = new TextBlock() { Text = "作物图片",0) };
            sp.Children.Add(zwxpText);
            zwxpButton.Content = sp;
            grid.Children.Add(zwxpButton);


            //专家会议
            Button zjhyButton = new Button() { Height = 22,48,HorizontalContentAlignment = HorizontalAlignment.Left };
            zjhyButton.Style = Application.Current.Resources["ContextMenuButton"] as Style;
            zjhyButton.Click += zjhy_MouseLeftButtonUp;
            Grid.SetColumnSpan(zjhyButton,2);
            sp = new StackPanel() { Orientation = Orientation.Horizontal };
            Image zjhyImage = new Image() { HorizontalAlignment = HorizontalAlignment.Left,0) };
            zjhyImage.source = new BitmapImage(new Uri("/MapClient;component/Images/pop-person.png",UriKind.RelativeOrAbsolute));
            sp.Children.Add(zjhyImage);
            TextBlock zjhyText = new TextBlock() { Text = "专家会议",0) };
            sp.Children.Add(zjhyText);
            zjhyButton.Content = sp;
            grid.Children.Add(zjhyButton);

            //现场联动
            Button xcldButton = new Button() { Height = 22,72,HorizontalContentAlignment = HorizontalAlignment.Left };
            xcldButton.Style = Application.Current.Resources["ContextMenuButton"] as Style;
            xcldButton.Click += xcld_MouseLeftButtonUp;
            Grid.SetColumnSpan(xcldButton,2);
            sp = new StackPanel() { Orientation = Orientation.Horizontal };
            Image xcldImage = new Image() { HorizontalAlignment = HorizontalAlignment.Left,0) };
            xcldImage.source = new BitmapImage(new Uri("/MapClient;component/Images/pop-link.png",UriKind.RelativeOrAbsolute));
            sp.Children.Add(xcldImage);
            TextBlock xcldText = new TextBlock() { Text = "现场联动",0) };
            sp.Children.Add(xcldText);
            xcldButton.Content = sp;
            grid.Children.Add(xcldButton);

            border.Child = grid;
            return border;
        }

        //
        //处理事件
        //
        void tjsp_MouseLeftButtonUp(object sender,RoutedEventArgs e)
        {
            //页面跳转,使用参数进行url传递 参数值为placeName(请注意)
            System.Windows.browser.HtmlPage.Window.Navigate(new Uri("../SensorMonitor/VedioList.aspx?AreaName=" + placeName,UriKind.RelativeOrAbsolute),"_self");
            Close();
        }

        void zwxp_MouseLeftButtonUp(object sender,RoutedEventArgs e)
        {
            //页面跳转
            System.Windows.browser.HtmlPage.Window.Navigate(new Uri("../SensorMonitor/Instantimage.aspx?AreaName=" + placeName,"_self");
            Close();
        }

        void zjhy_MouseLeftButtonUp(object sender,RoutedEventArgs e)
        {
            //页面跳转
            System.Windows.browser.HtmlPage.Window.Navigate(new Uri("http://www.baidu.com","_self");
            Close();
        }

        void xcld_MouseLeftButtonUp(object sender,"_self");
            Close();
        }
    }
}

4、MainPage.xaml及MainPage.xaml.cs代码如下:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:esri="http://schemas.esri.com/arcgis/client/2009"
             xmlns:toolkit="clr-namespace:ESRI.ArcGIS.Client.Toolkit;assembly=ESRI.ArcGIS.Client.Toolkit"
             xmlns:symbols="clr-namespace:ESRI.ArcGIS.Client.Symbols;assembly=ESRI.ArcGIS.Client"
             xmlns:local="clr-namespace:GrowthMonitor"
             xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
             xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             xmlns:interaction="http://schemas.microsoft.com/expression/2010/interactivity"
             xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             xmlns:slData="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
             x:Class="MapClient.MainPage" d:DesignHeight="300" d:DesignWidth="400" Loaded="UserControl_Loaded" mc:Ignorable="d">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.Resources>
            <esri:SimpleMarkerSymbol x:Key="DefaultMarkerSymbol" Size="12" x:Name="dms_Point" Style="Circle">
                <esri:SimpleMarkerSymbol.ControlTemplate>
                    <ControlTemplate>
                        <Grid x:Name="RootElement" RenderTransformOrigin="0.5,0.5" >
                            <Grid.RenderTransform>
                                <ScaleTransform ScaleX="1" ScaleY="1" />
                            </Grid.RenderTransform>
                            <visualstatemanager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="normal">
                                        <Storyboard>
                                            <DoubleAnimation BeginTime="00:00:00" 
                                                                      Storyboard.TargetName="RootElement" 
                                                                      Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)" 
                                                                      To="1" Duration="0:0:0.1" />
                                            <DoubleAnimation BeginTime="00:00:00" 
                                                                      Storyboard.TargetName="RootElement" 
                                                                      Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)" 
                                                                      To="1" Duration="0:0:0.1" />
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="MouSEOver">
                                        <Storyboard>
                                            <DoubleAnimation BeginTime="00:00:00" 
                                                                      Storyboard.TargetName="RootElement" 
                                                                      Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)" 
                                                                      To="1.5" Duration="0:0:0.1" />
                                            <DoubleAnimation BeginTime="00:00:00" 
                                                                      Storyboard.TargetName="RootElement" 
                                                                      Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)" 
                                                                      To="1.5" Duration="0:0:0.1" />
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </visualstatemanager.VisualStateGroups>
                            <Ellipse x:Name="ellipse"			                                        
                                                    Width="{Binding Symbol.Size}"
                                                    Height="{Binding Symbol.Size}" >
                                <Ellipse.Fill>
                                    <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5"
                                                                RadiusX="0.5" RadiusY="0.5">
                                        <GradientStop Color="Red" Offset="0.25" />

                                    </RadialGradientBrush>
                                </Ellipse.Fill>
                            </Ellipse>
                        </Grid>
                    </ControlTemplate>
                </esri:SimpleMarkerSymbol.ControlTemplate>
            </esri:SimpleMarkerSymbol>
            <esri:SimpleLinesymbol x:Key="DefaultLinesymbol" Color="Red" Width="6"  />
            <esri:SimpleFillSymbol x:Key="DefaultFillSymbol" BorderBrush="Red" BorderThickness="2" x:Name="sf_Point"/>

        </Grid.Resources>
        <esri:Map x:Name="myMap" IslogoVisible="False" Extent="114.289579051054,29.3907111115968,121.380372848428,33.7272787947227">
            <i:Interaction.Behaviors>
                <local:WheelZoom />
            </i:Interaction.Behaviors>
            <esri:Map.Layers>
                <esri:ArcGISTiledMapServiceLayer ID="BaseLayer" Url="http://192.168.2.5/arcgis/rest/services/AnHuiBase/MapServer"/>
                <!---特征图层-->
                <!--<esri:FeatureLayer ID="MyFeatureLayer" Url="http://192.168.2.5/arcgis/rest/services/AnHuiDynamic/MapServer/0">
                <esri:FeatureLayer.Clusterer>
                    <esri:FlareClusterer
            				FlareBackground="#99FF0000"
            				FlareForeground="White"
            				MaximumFlareCount="9"/>
                </esri:FeatureLayer.Clusterer>
                <esri:FeatureLayer.OutFields>
                    <sys:String>ID</sys:String>
                    <sys:String>Name</sys:String>
                </esri:FeatureLayer.OutFields>
                <esri:FeatureLayer.MapTip>
                    <Grid Background="Blue" Width="200" Height="200">
                        <StackPanel>
                            <TextBlock Text="{Binding [Name]}" Foreground="White" FontWeight="Bold" />
                        </StackPanel>
                    </Grid>
                </esri:FeatureLayer.MapTip>
            </esri:FeatureLayer>-->
                <!--Graphicslayer-->
                <esri:Graphicslayer ID="MyGraphicslayer">
                </esri:Graphicslayer>
            </esri:Map.Layers>
        </esri:Map>
        <Grid Height="60" HorizontalAlignment="Right" VerticalAlignment="Top"  Width="300">
            <Grid.ColumnDeFinitions>
                <ColumnDeFinition Width="0.128*"/>
                <ColumnDeFinition Width="0.142*"/>
                <ColumnDeFinition Width="0.14*"/>
                <ColumnDeFinition Width="0.15*"/>
                <ColumnDeFinition Width="0.14*"/>
                <ColumnDeFinition Width="0.14*"/>
                <ColumnDeFinition Width="0.15*"/>
            </Grid.ColumnDeFinitions>
            <Border x:Name="bZoomIn" BorderThickness="1" Margin="0,-1,1">
                <Border.Background>
                    <ImageBrush ImageSource="Images/i_zoomin.png" Stretch="None"/>
                </Border.Background>
            </Border>
            <Border x:Name="bZoomOut" BorderThickness="1" Grid.Column="1" Margin="3,-2,2,2">
                <Border.Background>
                    <ImageBrush ImageSource="Images/i_zoomout.png" Stretch="None"/>
                </Border.Background>
            </Border>
            <Border x:Name="bPan" BorderThickness="1" Grid.Column="2" Margin="2,1">
                <Border.Background>
                    <ImageBrush ImageSource="Images/i_pan.png" Stretch="None"/>
                </Border.Background>
            </Border>
            <Border x:Name="bPrevIoUs" BorderThickness="1" Grid.Column="3" Margin="4,1,5,-1">
                <Border.Background>
                    <ImageBrush ImageSource="Images/i_prevIoUs.png" Stretch="None"/>
                </Border.Background>
            </Border>
            <Border x:Name="bNext" BorderThickness="1" Grid.Column="4" Margin="4,-2" RenderTransformOrigin="1.385,0.545">
                <Border.Background>
                    <ImageBrush ImageSource="Images/i_next.png" Stretch="None"/>
                </Border.Background>
            </Border>
            <Border x:Name="bFullExtent" BorderThickness="1" Grid.Column="5" Margin="2,0" RenderTransformOrigin="1.385,0.545">
                <Border.Background>
                    <ImageBrush ImageSource="Images/i_globe.png" Stretch="None"/>
                </Border.Background>
            </Border>
            <Border x:Name="bFullScreen" BorderThickness="1" Grid.Column="6" Margin="8,0.545">
                <Border.Background>
                    <ImageBrush ImageSource="Images/i_widget.png" Stretch="None"/>
                </Border.Background>
            </Border>
        </Grid>

        <esri:Navigation Margin="5" HorizontalAlignment="Left" VerticalAlignment="Bottom"
                         Map="{Binding ElementName=myMap}"  >
        </esri:Navigation>
        <esri:MapProgressBar x:Name="MyProgressBar" 
			Map="{Binding ElementName=myMap}"
			HorizontalAlignment="Center" VerticalAlignment="Bottom"
			Width="200" Height="36"
			Margin="25"  />
        <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" Margin="0,0" VerticalAlignment="Top">
            <Button Style="{StaticResource darkButtonStyle}" Margin="3,0" >
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click" >
                        <local:ToggleFullScreenAction />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
                <Image Source="Images/Fullscreen-32.png" Height="24" Margin="-4"
							   ToolTipService.ToolTip="全屏"/>
            </Button>
        </StackPanel>
        <Button Content="查找" Height="23" HorizontalAlignment="Left" Margin="279,110,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="161,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
        <sdk:Label Height="28" HorizontalAlignment="Left" Margin="45,0" Name="label1" FontSize="15" Content="输入监测点名称:" VerticalAlignment="Top" Width="120" />
    </Grid>
</UserControl>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client.Symbols;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Tasks;
using System.Windows.Data;
using System.Runtime.Serialization;
using ESRI.ArcGIS.Client.Geometry;
using MapClient.UserControls;

namespace MapClient
{
    public partial class MainPage : UserControl
    {
        //一些列变量定义
        public string str = null; //用来接收aspx页面传递到xap中的参数字符串
        string[] infos = null;
        public string level = string.Empty; //市县等级 市=1/县=2
        public string areaId = string.Empty; //地区ID,包括市及县的编号
        public string color = string.Empty; //颜色值
        public string year = string.Empty; //年份
        public string cycleId = string.Empty; //生育周期编号

        public MainPage(Dictionary<string,string> paramsDic)
        {
            InitializeComponent();
            if (paramsDic.TryGetValue("STR",out str))
            {
                //获取到aspx页面传递过来的参数

            }
            //按照|进行拆分成每一个监测点的信息
            infos = str.Split('|');

            //初始化页面,开始地图加载条
            MyDrawObject = new Draw(myMap)
            {
                FillSymbol = LayoutRoot.Resources["DefaultFillSymbol"] as ESRI.ArcGIS.Client.Symbols.FillSymbol,DrawMode = DrawMode.Rectangle
            };

            MyDrawObject.DrawComplete += myDrawObject_DrawComplete;
        }


        private void UserControl_Loaded(object sender,RoutedEventArgs e)
        {
            FindGraphicsAndShowInMap("监测点");
        }


        private void Button_Click(object sender,RoutedEventArgs e)
        {
            FindGraphicsAndShowInMap("临泉监测点");
        }

        //#region 市界图层
        //public void FindCityGraphicsAndShowInMap(string conditions)
        //{
        //    // 初始化查找操作
        //    FindTask findCityTask = new FindTask("http://192.168.2.5/arcgis/rest/services/AnHuiDynamic/MapServer/");
        //    findCityTask.ExecuteCompleted += new EventHandler<FindEventArgs>(findCityTask_ExecuteCompleted);
        //    findCityTask.Failed += new EventHandler<TaskFailedEventArgs>(findCityTask_Failed);

        //    //初始化查找参数,指定Name字段作为小麦监测点层的搜素条件,并返回特征图层作为查找结果
        //    FindParameters findParameters = new FindParameters();
        //    findParameters.LayerIds.AddRange(new int[] { 2 });
        //    findParameters.SearchFields.AddRange(new string[] { "AreaID","NAME" });
        //    findParameters.ReturnGeometry = true;

        //    //要查找点的信息
        //    findParameters.SearchText = conditions;

        //    findCityTask.ExecuteAsync(findParameters);
        //}

        ////查找失败
        //void findCityTask_Failed(object sender,TaskFailedEventArgs e)
        //{
        //    MessageBox.Show("查找失败: " + e.Error);
        //}

        //void findCityTask_ExecuteCompleted(object sender,FindEventArgs e)
        //{
        //    // 清除先前的图层
        //    Graphicslayer graphicslayer = myMap.Layers["MyGraphicslayer"] as Graphicslayer;
        //    graphicslayer.Cleargraphics();

        //    // 检查新的结果
        //    if (e.FindResults.Count > 0)
        //    {
        //        //将查询出来的结果在地图上显示出来
        //        foreach (FindResult result in e.FindResults)
        //        {
        //            result.Feature.Symbol = LayoutRoot.Resources["DefaultFillSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
        //            graphicslayer.Graphics.Add(result.Feature);

        //            //左键菜单
        //            result.Feature.MouseLeftButtonDown += new MouseButtonEventHandler(Feature_MouseLeftButtonDown);
        //            result.Feature.MouseLeftButtonUp += new MouseButtonEventHandler(Feature_MouseLeftButtonUp);
        //            //右键菜单
        //            result.Feature.MouseRightButtonDown += new MouseButtonEventHandler(Feature_MouseRightButtonDown);
        //            result.Feature.MouseRightButtonUp += new MouseButtonEventHandler(Feature_MouseRightButtonUp);

        //        }
        //        //坐标自动定位
        //        ESRI.ArcGIS.Client.Geometry.Envelope selectedFeatureExtent = e.FindResults[0].Feature.Geometry.Extent;

        //        double expandPercentage = 30;

        //        double widthExpand = selectedFeatureExtent.Width * (expandPercentage / 100);
        //        double heightExpand = selectedFeatureExtent.Height * (expandPercentage / 100);

        //        ESRI.ArcGIS.Client.Geometry.Envelope displayExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(
        //        selectedFeatureExtent.XMin - (widthExpand / 2),//        selectedFeatureExtent.YMin - (heightExpand / 2),//        selectedFeatureExtent.XMax + (widthExpand / 2),//        selectedFeatureExtent.YMax + (heightExpand / 2));

        //        myMap.ZoomTo(displayExtent);
        //    }
        //    else
        //    {
        //        MessageBox.Show("没有发现匹配该搜索的记录!");
        //    }
        //}

        //#endregion

        #region 小麦监测点图层

        /// <summary>
        /// 根据条件查找监测点图层(0)
        /// </summary>
        /// <param name="conditions"></param>
        public void FindGraphicsAndShowInMap(string conditions)
        {
            // 初始化查找操作
            FindTask findTask = new FindTask("http://192.168.2.5/arcgis/rest/services/AnHuiDynamic/MapServer/");
            findTask.ExecuteCompleted += FindTask_ExecuteCompleted;
            findTask.Failed += FindTask_Failed;

            //初始化查找参数,指定Name字段作为小麦监测点层的搜素条件,并返回特征图层作为查找结果
            FindParameters findParameters = new FindParameters();
            findParameters.LayerIds.AddRange(new int[] { 0 });
            findParameters.SearchFields.AddRange(new string[] { "ID","Name" });
            findParameters.ReturnGeometry = true;

            //要查找点的信息
            findParameters.SearchText = conditions;

            findTask.ExecuteAsync(findParameters);
        }

        #region FindTask 查找任务开始
        // 查找结束时,开始绘制点到图层上
        private void FindTask_ExecuteCompleted(object sender,FindEventArgs args)
        {
            // 清除先前的图层
            Graphicslayer graphicslayer = myMap.Layers["MyGraphicslayer"] as Graphicslayer;
            graphicslayer.Cleargraphics();

            // 检查新的结果
            if (args.FindResults.Count > 0)
            {
                //将查询出来的结果在地图上显示出来
                foreach (FindResult result in args.FindResults)
                {
                    //赋值颜色值
                    this.dms_Point.Color = new SolidColorBrush(Colors.Red);
                    result.Feature.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
                    graphicslayer.Graphics.Add(result.Feature);

                    //左键菜单
                    result.Feature.MouseLeftButtonDown += new MouseButtonEventHandler(Feature_MouseLeftButtonDown);
                    result.Feature.MouseLeftButtonUp += new MouseButtonEventHandler(Feature_MouseLeftButtonUp);
                    //右键菜单
                    result.Feature.MouseRightButtonDown += new MouseButtonEventHandler(Feature_MouseRightButtonDown);
                    result.Feature.MouseRightButtonUp += new MouseButtonEventHandler(Feature_MouseRightButtonUp);

                }
                //坐标自动定位
                ESRI.ArcGIS.Client.Geometry.Envelope selectedFeatureExtent = args.FindResults[0].Feature.Geometry.Extent;

                double expandPercentage = 30;

                double widthExpand = selectedFeatureExtent.Width * (expandPercentage / 100);
                double heightExpand = selectedFeatureExtent.Height * (expandPercentage / 100);

                ESRI.ArcGIS.Client.Geometry.Envelope displayExtent = new ESRI.ArcGIS.Client.Geometry.Envelope(
                selectedFeatureExtent.XMin - (widthExpand / 2),selectedFeatureExtent.YMin - (heightExpand / 2),selectedFeatureExtent.XMax + (widthExpand / 2),selectedFeatureExtent.YMax + (heightExpand / 2));

                myMap.ZoomTo(displayExtent);
            }
            else
            {
                MessageBox.Show("没有发现匹配该搜索的记录!");
            }
        }

        //当查找失败时进行提示操作
        private void FindTask_Failed(object sender,TaskFailedEventArgs args)
        {
            MessageBox.Show("查找失败: " + args.Error);
        }

        #endregion FindTask 查找任务结束

        #endregion

        RichTextBox rtb;
        #region 鼠标左键事件开始
        void Feature_MouseLeftButtonUp(object sender,MouseButtonEventArgs e)
        {
            //鼠标左键,显示ToolTip信息
            Graphic g = sender as Graphic;
            //这里需要添加一个不消失的弹出框,并可以移入进行点击
            MapTips tips = new MapTips(rtb,g.Attributes["Name"].ToString().Trim(),g.Attributes["AreaID"].ToString().Trim(),"-1","-1");
            tips.Show(e.GetPosition(LayoutRoot));
        }

        void Feature_MouseLeftButtonDown(object sender,MouseButtonEventArgs e)
        {
            e.Handled = true;
        }
        #endregion 鼠标左键事件结束

        #region 鼠标右键事件开始
        void Feature_MouseRightButtonUp(object sender,MouseButtonEventArgs e)
        {
            Graphic g = sender as Graphic;
            RTBContextMenu menu = new RTBContextMenu(rtb,g.Attributes["Name"].ToString().Trim());
            menu.Show(e.GetPosition(LayoutRoot));
        }

        void Feature_MouseRightButtonDown(object sender,MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        #endregion 鼠标右键事件结束

        string _toolMode = "";
        List<Envelope> _extentHistory = new List<Envelope>();
        int _currentExtentIndex = 0;
        bool _newExtent = true;

        Image _prevIoUsExtentimage;
        Image _nextExtentimage;
        private Draw MyDrawObject;



        private void MyToolbar_ToolbarItemClicked(object sender,ESRI.ArcGIS.Client.Toolkit.SelectedToolbarItemArgs e)
        {
            MyDrawObject.IsEnabled = false;
            _toolMode = "";
            switch (e.Index)
            {
                case 0: // ZoomIn Layers
                    MyDrawObject.IsEnabled = true;
                    _toolMode = "zoomin";
                    break;
                case 1: // Zoom Out
                    MyDrawObject.IsEnabled = true;
                    _toolMode = "zoomout";
                    break;
                case 2: // Pan
                    break;
                case 3: // PrevIoUs Extent
                    if (_currentExtentIndex != 0)
                    {
                        _currentExtentIndex--;

                        if (_currentExtentIndex == 0)
                        {
                            _prevIoUsExtentimage.Opacity = 0.3;
                            _prevIoUsExtentimage.IsHitTestVisible = false;
                        }

                        _newExtent = false;

                        myMap.IsHitTestVisible = false;
                        myMap.ZoomTo(_extentHistory[_currentExtentIndex]);

                        if (_nextExtentimage.IsHitTestVisible == false)
                        {
                            _nextExtentimage.Opacity = 1;
                            _nextExtentimage.IsHitTestVisible = true;
                        }
                    }
                    break;
                case 4: // Next Extent
                    if (_currentExtentIndex < _extentHistory.Count - 1)
                    {
                        _currentExtentIndex++;

                        if (_currentExtentIndex == (_extentHistory.Count - 1))
                        {
                            _nextExtentimage.Opacity = 0.3;
                            _nextExtentimage.IsHitTestVisible = false;
                        }

                        _newExtent = false;

                        myMap.IsHitTestVisible = false;
                        myMap.ZoomTo(_extentHistory[_currentExtentIndex]);

                        if (_prevIoUsExtentimage.IsHitTestVisible == false)
                        {
                            _prevIoUsExtentimage.Opacity = 1;
                            _prevIoUsExtentimage.IsHitTestVisible = true;
                        }
                    }
                    break;
                case 5: // Full Extent
                    myMap.ZoomTo(myMap.Layers.GetFullExtent());
                    break;
                case 6: // Full Screen
                    Application.Current.Host.Content.IsFullScreen = !Application.Current.Host.Content.IsFullScreen;
                    break;
            }
        }

        private void myDrawObject_DrawComplete(object sender,DrawEventArgs args)
        {
            if (_toolMode == "zoomin")
            {
                myMap.ZoomTo(args.Geometry as ESRI.ArcGIS.Client.Geometry.Envelope);
            }
            else if (_toolMode == "zoomout")
            {
                Envelope currentExtent = myMap.Extent;

                Envelope zoomBoxExtent = args.Geometry as Envelope;
                MapPoint zoomBoxCenter = zoomBoxExtent.GetCenter();

                double whRatioCurrent = currentExtent.Width / currentExtent.Height;
                double whRatioZoomBox = zoomBoxExtent.Width / zoomBoxExtent.Height;

                Envelope newEnv = null;

                if (whRatioZoomBox > whRatioCurrent)
                // use width
                {
                    double mapWidthPixels = myMap.Width;
                    double multiplier = currentExtent.Width / zoomBoxExtent.Width;
                    double newWidthMapUnits = currentExtent.Width * multiplier;
                    newEnv = new Envelope(new MapPoint(zoomBoxCenter.X - (newWidthMapUnits / 2),zoomBoxCenter.Y),new MapPoint(zoomBoxCenter.X + (newWidthMapUnits / 2),zoomBoxCenter.Y));
                }
                else
                // use height
                {
                    double mapHeightPixels = myMap.Height;
                    double multiplier = currentExtent.Height / zoomBoxExtent.Height;
                    double newHeightMapUnits = currentExtent.Height * multiplier;
                    newEnv = new Envelope(new MapPoint(zoomBoxCenter.X,zoomBoxCenter.Y - (newHeightMapUnits / 2)),new MapPoint(zoomBoxCenter.X,zoomBoxCenter.Y + (newHeightMapUnits / 2)));
                }

                if (newEnv != null)
                    myMap.ZoomTo(newEnv);
            }
        }

        private void MyMap_ExtentChanged(object sender,ExtentEventArgs e)
        {
            if (e.OldExtent == null)
            {
                _extentHistory.Add(e.NewExtent.Clone());
                return;
            }

            if (_newExtent)
            {
                _currentExtentIndex++;

                if (_extentHistory.Count - _currentExtentIndex > 0)
                    _extentHistory.RemoveRange(_currentExtentIndex,(_extentHistory.Count - _currentExtentIndex));

                if (_nextExtentimage.IsHitTestVisible == true)
                {
                    _nextExtentimage.Opacity = 0.3;
                    _nextExtentimage.IsHitTestVisible = false;
                }

                _extentHistory.Add(e.NewExtent.Clone());

                if (_prevIoUsExtentimage.IsHitTestVisible == false)
                {
                    _prevIoUsExtentimage.Opacity = 1;
                    _prevIoUsExtentimage.IsHitTestVisible = true;
                }
            }
            else
            {
                myMap.IsHitTestVisible = true;
                _newExtent = true;
            }
        }

        private void button1_Click(object sender,RoutedEventArgs e)
        {
            if (this.textBox1.Text == "")
            {
                FindGraphicsAndShowInMap("0");
            }
            else
            {
                FindGraphicsAndShowInMap(this.textBox1.Text.Trim());
            }
        }

    }
}

效果图如下:鼠标点击后弹出窗体,及鼠标右键弹出快捷菜单,如下:

以后继续完善,不断改进。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐