如何从WPF中的另一个窗口绑定到MainWindow中的控件?

时间:2013-01-22 17:40:14

标签: wpf xaml binding

基本上,我的问题已出现在标题中: 当我有一个MainWindow如下:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:easycache"
        xmlns:map="clr-namespace:MapControl;assembly=MapControl.WPF"
        x:Class="easycache.MainWindow"
        x:Name="MainWindow1"
        Title="easycache"
        Height="600"
        Width="850">
  <map:Map Grid.Column="2"
           Grid.Row="1"
           Name="map"
           IsManipulationEnabled="True"
           LightForeground="Black"
           LightBackground="White"
           DarkForeground="White"
           DarkBackground="#FF3F3F3F"
           Center="0.0,0.0"
           ZoomLevel="0.0"
           TileLayer="{Binding Source={StaticResource TileLayersView}, Path=CurrentItem}" />

在我的窗口2中,我有:

<map:Map Name="map" IsManipulationEnabled="False"
                 LightForeground="Black" LightBackground="White" DarkForeground="White" DarkBackground="#FF3F3F3F"
                 Center="0.0,0.0" ZoomLevel="{Binding ?????}">

我想将Window2中地图的ZoomLevel绑定到MainWindow中地图的ZoomLevel。我怎样才能做到这一点?

此致 Ialokim

1 个答案:

答案 0 :(得分:0)

在您的MainWindow代码隐藏中,使用公共get访问器创建一个公共属性,如下所示:

private double _mapZoom;
public double MapZoom //I assume that ZoomLevel is of type double, if not use the correct type
{
    get { return _mapZoom; }
    set { _mapZoom = value; OnPropertyChanged("MapZoom"); }
}

你必须在你的MainWindow中实现INotifyPropertyChanged接口(到处都有一百万个例子,不需要进入这里)。

然后,将地图的ZoomLevel属性绑定到MapZoom属性,如下所示:

<map:Map Name="map" ZoomLevel="{Binding RelativeSource={RelativeSource Self}, Path=MapZoom}, Mode=TwoWay"/>

为此,Window的DataContext必须是Window本身,在Window的构造函数中需要一行:

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this; //add this line
    }

你需要一种方法让第二个窗口调用主窗口,这样你就可以创建一个静态属性来返回主窗口中的当前实例:

    private static MainWindow _instance;
    public static MainWindow Instance
    {
        get
        {
            if (_instance == null)
                _instance = new MainWindow();
            else
                _instance = this;

            return _instance;
        }
    } //you have to make sure to create ONE instance of MainWindow before getting this property, and not to create more instances elsewhere

现在,您将让MainWindow公开一个公共属性,该属性绑定到地图的缩放。

因此,在第二个窗口中创建一个指向主窗口实例的属性:

   public MainWindow Main { get { return MainWindow.Instance; }

最后,您可以将第二个地图的缩放绑定到公共属性MapZoom,它是Main的成员:

<map:Map Name="map2" ZoomLevel="{{Binding RelativeSource={RelativeSource Self}, Path=Main.MapZoom}, Mode=TwoWay"}">

在此绑定中,“Main”通过window2的公共属性引用MainWindow实例(在window2中设置this.DataContext = this;以及访问.MapZoom属性。

默认情况下,您在XAML中创建的所有对象都是私有的,因此您必须使用带有get / set访问器的公共属性显式地公开它们,以使它们可以从外部访问。

如果有效,请告诉我,我没有创建应用来测试代码。此致!

相关问题