2012-11-06 66 views
-1

,所以我有这样的用户控件:WPF绑定到另一个控件的属性

<UserControl x:Class="Client.SpectrumSpace" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:my="clr-namespace:Client" 
      mc:Ignorable="d" d:DesignHeight="150" d:DesignWidth="350"> 
    <Canvas> 
     <Rectangle Width="350" Height="150" Fill="Transparent" Stroke="White" StrokeThickness="1"> 
      <Rectangle.ContextMenu> 
       <ContextMenu Name="contextMenu"> 
        <MenuItem Name="ctxItem1" Header="AntennaName" 
           IsEnabled="{Binding MainWindow.availeableAntennas[0]}"/> 
       </ContextMenu> 
      </Rectangle.ContextMenu> 
     </Rectangle> 
    </Canvas> 
</UserControl> 

,正如你可以看到我尝试了MainWindow.availableAntennas [0]属性绑定到MenuItem.IsEnabled财产

这是我宣布MainWindow类数组:

public bool[]  availableAntennas = new bool[9]; 

我的问题是,IsEnabled属性始终是真,是的,我仔细检查了该availeableAntennas [0]是假的,所以我在这里做错了什么?

+0

我总觉得这的cheatsheet帮助:http://www.nbdtech.com/Free/WpfBinding.pdf –

回答

2

您应该使用绑定表达式的"RelativeSource"

干杯

+0

我试过的IsEnabled =“{结合MainWindow.availeableAntennas [0]的RelativeSource = {的RelativeSource AncestorType = {x:Type Window}}}“它没有工作,我是否再次犯错? :S –

+0

什么是您所指的MainWindow?我认为它应该是“{Binding availeableAntennas [0],RelativeSource = {RelativeSource AncestorType = {x:Type Window}}}”。当您使用RelativeSource时,datacontext将是与relativesource表达式匹配的对象。此外,我不确定你的窗口类中的公共变量。 – Rikki

+0

MainWindow是我的程序的主窗口,它是启动时启动的窗口。我试图将xaml代码更改为您提供的代码,但它仍然是一样的 –

1

对我来说,它看起来像它可能是一个几件事情或全部:

  • 您不能绑定到一个字段必须是一个属性 - 公共BOOL [ ] availableAntennas =新布尔[9]
  • 甲错字 - availeableAntennas与availableAntennas
  • DataContext的必须被设置(这不是显而易见的张贴),
  • 您绑定的类必须实现INotifyPropertyChanged。
+0

你是正确的我的代码中有一个错字,但它仍然没有纠正我的问题,并通过设置datacontext你的意思是DataContext =“{Binding RelativeSource = {RelativeSource Self}}”?因为我也没有成功 –

+0

在您的UserControl的ctor中,将其DataContext设置为您要绑定到的类。此外,这个类(数据上下文)必须实现INotifyPropertyChanged(我更新了我的响应以包含此)。 –