zoukankan      html  css  js  c++  java
  • 在WPF中如何使用RelativeSource绑定

    在WPF绑定的时候,指定绑定源时,有一种办法是使用RelativeSource。

    这种办法的意思是指当前元素和绑定源的位置关系。

    第一种关系: Self

    举一个最简单的例子:在一个StackPanel中,有一个TextBlock。

    <TextBlock FontSize="18" FontWeight="Bold" Margin="10" 
                     Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>

    如果想让textbox的width和height相同,通过设置属性Height="{Binding RelativeSource={RelativeSource Self},Path=Width}" 就可以实现。

    第二种关系:TemplatedParent

    例如为一个Button写一个样式,修改Button为椭圆型。同时需要椭圆的背景色和Button的背景色相同。

    <Style TargetType="{x:Type Button}">
                <Setter Property="Background" Value="Green"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Grid>
                                <Ellipse>
                                    <Ellipse.Fill>
                                        <SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
                                    </Ellipse.Fill>
                                </Ellipse>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

    在这个例子中 TemplateParent就是指的Button

    第三种关系:AncestorType

    指定绑定源为某个父元素

    <Grid>

              <Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/>

         </Grid>

    这个例子中Label的背景色和Grid的背景色一样。

  • 相关阅读:
    初學C#窗口事件
    Visual Studio 2005.net 代码段(Snippet)丢失的解决方案
    使用C#代码段,提高工作效率(C# code snippet)
    同时拥有静态IP和动态IP
    让XP启动时不加载Autoexec.bat
    C#中构造函数和析构函数的用法
    C# 輸入關鍵字後按Tab鍵無法帶出相關內容
    C# 打開文件
    system.net.mail 與system.web.mail的區別
    C#中的建立事件
  • 原文地址:https://www.cnblogs.com/nimorl/p/9081780.html
Copyright © 2011-2022 走看看