xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window15" Height="300" Width="300">
<Grid>
<StackPanel Name="sp1">
<Grid Name="gd1">
<StackPanel Name="sp2">
<Grid Name="gd2">
<!--<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType=StackPanel, Mode=FindAncestor}, Path=Name}"></TextBlock>-->//xaml实现
<TextBlock Name="txt"></TextBlock>
</Grid>
</StackPanel>
</Grid>
</StackPanel>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace XamlTest
{
/// <summary>
/// Interaction logic for Window15.xaml
/// </summary>
public partial class Window15 : Window
{
public Window15()
{
InitializeComponent();
Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(StackPanel), 1);
b.Path = new PropertyPath("Name");
txt.SetBinding(TextBlock.TextProperty, b);
}
}
}