WPF的控件Binding笔记

                                             WPF的控件Binding笔记

1 绑定一个普通的属性

在类中定义了一个自定义的 content属性(非依赖项属性),在xaml的button的content属性中绑定它。

Content="{Binding ppcontent,ElementName=myform}" ,此处的ElementName=myform是需要的,myform是我给主界面起的名字,因为绑定的自定义属性在主界面中

(2)如果直接删掉ElementName=myform不能成功绑定,但是如果在代码构造函数中使用this.maingrid.DataContext=this

       那么删除ElementName=myform 也能绑定成功。

        注意maingrid是可视化树的最外层,所以自动向上寻找属性到maingrid这一层就停止了

using System.Windows.Shapes;
namespace wpftest1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //在button的任意父级如maingrid 给DataContext赋值都能实现
            //this.maingrid.DataContext=this  
        }
        #绑定的属性最好是依赖属性 不然可能无法动态更新
        public static readonly DependencyProperty ppcontentProperty = DependencyProperty.Register("ppcontent", typeof(string), typeof(MainWindow ));
        public string ppcontent {
            get
            {
                return (string)GetValue(ppcontentProperty );
            }

            set
            {
                SetValue(ppcontentProperty , value);
            }
        }
  
       
    }
}
<Window x:Name="form" x:Class="wpftest1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:wpftest1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="maingrid" >
        <Button x:Name="button" Content="{Binding ppcontent,ElementName=form}" HorizontalAlignment="Left" Margin="62,104,0,0" VerticalAlignment="Top" Width="152" Height="92" Foreground="#FFED1313">
            <Button.Background>
                <ImageBrush ImageSource="images/boshimao.png"/>
            </Button.Background>
        </Button>

    </Grid>
</Window>


2 例子2

 <TextBlock Text="{Binding Path=name}"></TextBlock>并没有显式的定义source绑定会自动向上级的上下文中寻找name属性



namespace wpftest1
{
    /// <summary>
    /// Interaction logic for stack1.xaml
    /// </summary>
    public partial class stack1 : Window
    {
        public stack1()
        {
            InitializeComponent();
           
        }
    }

    public class Student
    {
        public string name { get; set; }
    }
}


<Window x:Class="wpftest1.stack1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:wpftest1"
        
        mc:Ignorable="d"
        Title="stack1" Height="300" Width="300">
    <Grid>
        <StackPanel HorizontalAlignment="Left" Height="138" Margin="79,74,0,0" VerticalAlignment="Top" Width="127">
            <StackPanel.DataContext>
                <local:Student name="TOM"></local:Student>
            </StackPanel.DataContext>

            <TextBlock Text="{Binding Path=name}"></TextBlock>
        </StackPanel>
        
         </Grid>
    
</Window>

注意的是binding 的源不指定,默认的是当前控件的DataContext,并不是当前控件的实体类.

2 静态属性

//static1.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="text">路漫漫其修远兮,吾将上下而求索!
</sys:String>
</ResourceDictionary>


在使用资源的地方连接到独立的资源文件上
XAML代码例如以下:
<Window x:Class="Demo009.MainWindow"
        xmlns="http://sche1mas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Resource Files" FontSize="30">
     <Window.Resources>
        
        <ResourceDictionary>
            <!--other resources can be here-->
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="imagebutton2.xaml" />
                <ResourceDictionary Source="imagebutton3.xaml" />
                <ResourceDictionary Source="static1.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <sys:String x:Key="text2">苟以国家生死一,其因祸福趋避之!</sys:String>
        </ResourceDictionary>
      
    </Window.Resources>
    <StackPanel>
        <TextBlock Text="{StaticResource text}" />
    </StackPanel>
</Window>

3 简单的定义图片文字按钮

<Button HorizontalAlignment="Left" Margin="222,151,0,0" VerticalAlignment="Top" Width="259" Height="52">
            <WrapPanel Height="52" Width="259">
                <Image Height="52" Width="61" Source="images/返回.png"/>
                <TextBlock TextWrapping="Wrap" Text="数据管理" Width="197" FontSize="22" VerticalAlignment="Center" Padding="40,0,0,0"/>
            </WrapPanel>
</Button>
        

<Button HorizontalAlignment="Left" Margin="249,259,0,0" VerticalAlignment="Top" Width="259" Height="52">
         
         <Image Height="52" Width="61" Source="images/返回.png"/>
               
 </Button>

4  RelativeSource绑定

{Binding RelativeSource={RelativeSource Self}  是说当前的属性绑定的源是当前控件,如下面的例子是说绑定的源是当前的

TextBlock实例

<TextBlock Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}" >

</TextBlock>

在Template模板种可以使用TemplateParent 或者TemplateBinding 绑定的是当前模板对应的控件如下面的例子指的是Button的实例

<Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
      <Border x:Name="PART_Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="{TemplateBinding CornerRadius}"/>

                            <Ellipse>
                                <Ellipse.Fill>
                                    <SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
                                </Ellipse.Fill>
                            </Ellipse>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

   使用AncestorType 可以连接父级的属性

  RelativeSource={RelativeSource FindAncestor,  AncestorType={x:Type Grid}}}可以简化为

  RelativeSource={RelativeSource   AncestorType={x:Type Grid}}}


<Grid>

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


</Grid>

5  使用ElementName 绑定其他控件的属性

<UserControl x:Class="WpfApp1.SquareView"
             xmlns:local="clr-namespace:WpfApp1"
             xmlns:myconverter="clr-namespace:WpfApp1.converter" //定义的命名空间
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="100">
    <UserControl.Resources>
        //添加一个转换器实例
        <myconverter:SizeChangeByRate x:Key="circlesize"></myconverter:SizeChangeByRate>
    </UserControl.Resources>
    <Grid x:Name="squaregrid">
        <Ellipse x:Name="circle"  Width="{Binding ElementName=squaregrid,Path=ActualWidth,Converter={StaticResource circlesize}}" Height="{Binding ElementName=squaregrid,Path=ActualHeight,Converter={StaticResource circlesize}}" Fill="#FF14C56F"></Ellipse>
    </Grid>
</UserControl>

再绑定的同时也可以同时Converter 给绑定的值加转化类

namespace WpfApp1.converter
{
    public class SizeChangeByRate : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double size = (double)value;
            return  size * 0.5;
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值