C# wpf绑定到另一个控件属性

C# wpf绑定到另一个控件属性,c#,wpf,binding,C#,Wpf,Binding,我有一个用户控件: <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.openxmlf

我有一个用户控件:

<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>
我的问题是IsEnabled属性始终为true,是的,我仔细检查了AvailableAttennas[0]是否为false,那么我在这里做错了什么?

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


干杯

对我来说,可能是几件事,也可能是全部:

  • 您不能绑定到字段,它必须是属性-public bool[]availableAntennas=new bool[9]
  • 一个打字错误-可用的天线vs.可用的天线
  • 必须设置datacontext(这在您的帖子中并不明显)
  • 绑定到的类必须实现INotifyPropertyChanged

我尝试了IsEnabled=“{Binding Main Window.AvailableAttennas[0],RelativeSource={RelativeSource AncestorType={x:Type Window}}}}}”,但它不起作用,我又做错了吗你指的是哪个主窗口?!我认为它应该是“{Binding availableantennas[0],RelativeSource={RelativeSource AncestorType={x:Type Window}}”。使用RelativeSource时,datacontext将是与RelativeSource表达式匹配的对象。另外,我不确定window类中的公共变量。MainWindow是我的程序的主窗口,在启动时启动。我试图将xaml代码更改为您提供的代码,但仍然是一样的。到底发生了什么?为什么定义变量?做什么?你能帮我解决这个问题吗?先生,你需要一个模型视图。一个从DependencyObject继承的类和一个dependency属性,正如您可能会问的,我将解释如何定义它。您应该将主DataContext(可能在主窗口的DataContext中)设置为该对象的实例,并将所有用户控件绑定到该对象。我一直觉得这个备忘单很有用:你是对的,我的代码中有一个输入错误,但它仍然没有纠正我的问题,通过设置datacontext,你的意思是datacontext=“{Binding RelativeSource={RelativeSource Self}”?因为我也这样做了,但没有成功在UserControl的ctor中,将其DataContext设置为要将其绑定到的类。另外,这个类(数据上下文)必须实现INotifyPropertyChanged(我更新了我的响应以包含这个)。
public  bool[]      availableAntennas   = new bool[9];