c# - 如何从另一个表单引用我的 Bing map 元素?

标签 c# winforms user-controls bing-maps

我在 UserControl1.xaml 文件中有一个 Bing map 元素:

<UserControl x:Class="MyMaps.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:m="clr-namespace:Microsoft.Maps.MapControl.WPF;assembly=Microsoft.Maps.MapControl.WPF">
    <Grid>
        <m:Map CredentialsProvider="Gr8GooglyMoogly" x:Name="myMap" />
    </Grid>
</UserControl>

我可以像这样从它所在的 Form1 访问它:

this.userControl11.myMap.Mode = new RoadMode();

...但是当我尝试从另一种形式访问它时,这些尝试都不起作用:

userControl11.myMap.Children.Add(pin); // does not exist in the current context
Form1.userControl11.myMap.Children.Add(pin); // inaccessible due to its protection level
UserControl1.myMap.Children.Add(pin); // object reference is required for the static field, ...

如何从另一个表单获取 UserControl 的句柄?

更新

使用 Reza 的注释将 map 的 Modifier 属性从 Private 更改为 Public,并使用 the link provided 中显示的方法,以下作品:

var frmMain = new Form1();
frmMain.userControl11.myMap.Children.Add(pin);

更新 2

Reza 的想法非常奏效。这是我测试它以验证的方式:

在“表格 2”(mdlDlgFrm_AddNewLocation)中:

// to access map on main form (Form1)
private Form1 frmMain;

// second constructor so as to access map on main form (to add pushpins)
public mdlDlgFrm_AddNewLocation(Form1 f1)
{
    InitializeComponent();
    this.frmMain = f1;
    // test
    AddPushpin("blaJustATest");
}

private void AddPushpin(string fullAddress)
{
    Pushpin pin = new Pushpin();
    // "brute-forcing" the coordinates for this test
    pin.Location = new Location(37.1481402218342, -119.644248783588); // Interesting location: out in the "boondocks" between Oakhurst and Auberry
    this.frmMain.userControl11.myMap.Children.Add(pin);
}

...和从主窗体(窗体 1)调用“窗体 2”:

private void addLocationToolStripMenuItem_Click(object sender, EventArgs e)
{
    mdlDlgFrm_AddNewLocation frmAddNewLocation = new mdlDlgFrm_AddNewLocation(this);
    frmAddNewLocation.ShowDialog(this);
    frmAddNewLocation.Dispose()
}

最佳答案

当您创建新表单时,您必须将当前表单作为参数发送给新表单的创建者,您可以在其中使用您提交的实例对该实例进行更改。

关于c# - 如何从另一个表单引用我的 Bing map 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65752504/

相关文章:

c# - 开放通用类型不会在目录中注册

c# - 过滤列表框

jquery - 尝试使用 <%= %> 访问 jquery 中的 asp 变量时不断收到 '[object Object]'

c# - 如何在使用 MVVM 模式时继承 WPF 中的 View ?

c# - WPF 和 C# : Create an override for a datagrid within a user control?

c# - 如何用空格表示枚举值?

c# - EPPlus:创建排序列

c# - 有没有办法为 ModelMetadata.RelatedEntities 获取 ModelMetadata.Properties?

C# 断点改变行为

c# - 将字符串转换为按钮