wpf RelativeSource绑定

科技资讯 投稿 5800 0 评论

wpf RelativeSource绑定

RelativeSource有四种类型

FindAncestor

PreviousData

a.Self

Self用于绑定源和绑定目标相同的场景中。对象的一个属性与同一对象的另一个属性绑定。

<Grid>
    <Ellipse Width="{Binding RelativeSource={RelativeSource Self}, Path=Height}"
             Height="100"
             Fill="Black" />
</Grid>

 

b.FindAncestor

顾名思义,当绑定源是绑定目标的祖先(父级)之一时使用此选项。使用FindAncestor扩展,可以找到任何级别的祖先。
             

<Grid Name="Parent_3">
    <StackPanel Name="Parent_222"
                Width="100"
                HorizontalAlignment="Center"
                VerticalAlignment="Center">
        <StackPanel Name="Parent_2"
                    Width="100"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center">
            <Border Name="Parent_1">
                <StackPanel x:Name="Parent_0"
                            Orientation="Vertical">
                    <!--  下面这个按钮Content得到:Parent_2  -->
                    <Button Height="50"
                            Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=2}, Path=Name}" />
                    <!--  下面这个按钮Content得到:Parent_0  -->
                    <Button Height="50"
                            Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}, AncestorLevel=1}, Path=Name}" />
                    <!--  下面这个按钮Content得到:Parent_0  -->
                    <Button Height="50"
                            Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}}, Path=Name}" />
                </StackPanel>
            </Border>
        </StackPanel>
    </StackPanel>
</Grid>

 

c.TemplatedParent

    <Window.Resources>
        <ControlTemplate x:Key="template1">
            <!--
                在应用模板时,按钮的Background(Beige)与椭圆的Fill属性相对绑定,Content(Click me)与ContentPresenter的Content属性相对绑定。依赖值生效并给出以下输出。
            -->
            <Canvas>
                <Ellipse Width="155"
                         Height="110"
                         Fill="Black" />
                <Ellipse Width="150"
                         Height="100"
                         Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background}" />
                <ContentPresenter Margin="35"
                                  Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}" />
            </Canvas>
        </ControlTemplate>
    </Window.Resources>
<Button Height="0"
                        Margin="5"
                        Background="Beige"
                        Content="Click me"
                        FontSize="18"
                        Template="{StaticResource template1}" />

 

d.PreviousData

 

编程笔记 » wpf RelativeSource绑定

赞同 (27) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽