【问题标题】:Bind to Property of Parent Element in Silverlight在 Silverlight 中绑定到父元素的属性
【发布时间】:2010-12-11 15:02:55
【问题描述】:

我正在尝试将 UserControl 中元素的属性绑定到 Silverlight 中 UserControl 本身的属性集。我确信它应该很简单,但我还没有设法让它与 RelativeSource 或 ElementName 绑定一起工作。在此示例中,我希望 Rectangle 为绿色(或任何 UserControl 的 Background 属性设置为)。

<UserControl x:Class="MyUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="40" Height="40" Background="Green" x:Name="root">
    <Grid x:Name="LayoutRoot" Background="White">
        <Rectangle x:Name="indicatorRectangle" Fill="{Binding Path=Background, ElementName=root}" Margin="0,0,26,0"  />
    </Grid>
</UserControl>

有人知道正确的绑定语法吗?

【问题讨论】:

    标签: silverlight data-binding user-controls


    【解决方案1】:

    试试这个:

    <UserControl ... Background="Green" x:Name="root">    
      <Grid x:Name="LayoutRoot" Background="White">        
        <Rectangle x:Name="indicatorRectangle" 
             Fill="{Binding Background, ElementName=root}" Width="10" Height="10"  />
      </Grid>
    </UserControl>
    

    在我为矩形指定宽度和高度之前,它对我不起作用。

    【讨论】:

      【解决方案2】:

      有趣的是,我在原始问题中发布的 XAML 在 VS2010 中可以正常工作,所以我认为这是已在最新的 Silverlight 中修复的问题

      【讨论】:

        【解决方案3】:

        请记住,如果您使用用户控件并将名称(在 Silverlight 4.0、Visual Studio 10 中)设置为 x:Name=,此代码将会中断。

        【讨论】:

          【解决方案4】:

          这采用 MyUserControl 类型的第一个祖先并绑定到它。

          xmlns:controls="namespace of your control" ...
          
          <Rectangle x:Name="indicatorRectangle" Fill="{Binding Path=Background 
          RelativeSource={RelativeSource AncestorLevel=1,AncestorType=controls:MyUserControl}"/>
          

          【讨论】:

            猜你喜欢
            • 2011-01-27
            • 1970-01-01
            • 2017-07-20
            • 2011-01-21
            • 2011-05-11
            • 2012-06-12
            • 1970-01-01
            • 2013-09-22
            • 1970-01-01
            相关资源
            最近更新 更多