RelativeSource and Popup

前端 未结 4 1981
萌比男神i
萌比男神i 2020-12-10 16:19

The problem is that RelativeSource does not work in the following case. I use silverlight 5.

//From MainPage.xaml


        
相关标签:
4条回答
  • 2020-12-10 16:34

    Popups are not part of the visual tree.

    Relative Source "Gets or sets the binding source by specifying its location relative to the position of the binding target (MSDN)". Since Popups are not part of the visual tree of the control that is showing it, it will not be able to resolve anything outside of the popup.

    0 讨论(0)
  • 2020-12-10 16:39

    Popup is like ContextMenu , ToolTip controls , They are not added to the VisualTree. For this you will have to do like

    <Grid x:Name="LayoutRoot" Height="100" Width="200" Background="Black">
        <Popup Grid.Row="0"  x:Name="popup" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}">
            <TextBlock Text="{Binding DataContext, ElementName=popup}" Background="Red" Width="30" Height="30" />
        </Popup>
    </Grid>
    
    public MainWindow()
        {
            InitializeComponent();
            DataContext = "abcd";
            popup.PlacementTarget = LayoutRoot; 
        }
    

    I hope this will help.Not like in case of ContextMenu or Tooltip , here you will also have to specify the PlacementTarget.

    0 讨论(0)
  • 2020-12-10 16:42

    You can make small hack: setup DataContext via resources.

    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="DataContext" Value="{Binding ElementName=myGrid, Path=DataContext}" />
        </Style>
    </Grid.Resources>
    
    0 讨论(0)
  • 2020-12-10 16:49

    As others have mentioned, it's because the Popup is not part of the visual tree. Instead, you can use the Popup's PlacementTarget property to get back to the visual tree:

    <Grid x:Name="LayoutRoot" Background="White" Height="100" Width="200">
        <Popup IsOpen="True">
            <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Popup}}, 
                                      Path=PlacementTarget.DataContext}" />
        </Popup>
    </Grid>
    
    0 讨论(0)
提交回复
热议问题