• 认识wpf中binding类型


     典型的Binding具有四个重要组成部分:目标对象binding target object)、目标对象属性target property)、数据源binding source)、Path(用于指明要从数据源中取得的值,就是我们通常写的属性名称)

    用控件作为数据源s

    看下面一个例子:

    要求slider与textbox中内容作相同的变化:

    <TextBox Height="23" Margin="10,10,10,0" Name="textBox1" VerticalAlignment="Top" Text="{Binding ElementName=slider1, Path=Value}" />
            <Slider Height="21" Margin="10s,40,10,0" Name="slider1" VerticalAlignment="Top" Maximum="100" />

    目标对象:TextBox;

    目标对象的属性:TextBox的Text属性 

    数据源:slider1;

    Path:数据源slider1的value值

    一个CLR 对象作为数据源,将其中一个属性值Binding到某个UIElement的属性上,以自定义的类为例:

      在我们项目组日常的工作中,经常需要自己写一个类,并且拿它的实例当作数据源,为类定义一些Property,用来为Binding提供Path

    例如:

     <TextBox Text=”{Binding Source=userinfo, Path=usernames}” ,

    怎样做到类变化时,让textbox也变化s

      让这个类实现INotifyPropertyChanged接口。实现这个接口的目的是当Source的属性值改变后通知Binding(不然人家怎么知道源头的数据变了并进行联动协同呢?),好让Binding把数据传输给Target

    例如:

    public class Userinfo: INotifyPropertyChanged
    {
     public event PropertyChangedEventHandler PropertyChanged; // 这个接口仅包含一个事件而已
     private string usercode;
     public string usercode
     {
      get { return usercode; }
      set
      {
       usercode= value;
       if (this.PropertyChanged != null)
       {
        this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("usercode")); // 通知Binding是“usercode”这个属性的值改变了
       }
      }
     }
     private string name;
     public string Name
     {
      get { return name; }
      set
      {
       name = value;
       if (this.PropertyChanged != null)
       {
        this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name")); // 通知Binding是“Name”这个属性的值改变了
       }
      }
     }
     以DataContext作为数据源

    DataContext是按照Element Tree向下继承的,并且决定这WPF在运行时能否找到我们所制定的Source对象,当我们有大量的Element需要与一个数据源中的众多属性实现Binding时,我们可以直接在一个公共Parent ElementDataContext上设置这一对象(甚至可以是整个windowpage上),这将会极大的加少我们重复的代码量,同时也会是程序更加可读。

    实例:

    <WrapPanel Grid.Row="1" Orientation="Horizontal" >

    <StackPanel Orientation="Horizontal" Margin="5,2,5,2">

        <TextBlock Text="ContactID:" TextAlignment="Center" />

    <TextBox Text="{Binding ElementName=listView1, Path=SelectedItem.ContactID}" MinWidth="100" />

     

    可以改为用DataContext,listView1中被选定的记录listView1.SelectedItem)作为DataContext放在公共Parent Element上,做法如下: 

    <WrapPanel Grid.Row="1" Orientation="Horizontal" DataContext="{Binding ElementName=listView1, Path=SelectedItem}">

    <StackPanel Orientation="Horizontal" Margin="5,2,5,2">

        <TextBlock Text="ContactID:" TextAlignment="Center" />

        <TextBox Text="{Binding ContactID}" MinWidth="100" />

    </StackPanel>

  • 相关阅读:
    c# 类中使用ResolveUrl
    IIS7日志中时间与系统时间不一致的原因
    IIS日志-网站运维的好帮手
    精通 JS正则表达式
    word 标题序号
    rtx 二次开发,查找所有部门
    【云计算】Docker容器时间同步如何配置?
    【云计算】Docker多进程管理方案-cfengine && supervisord
    【Python】装饰器实现日志记录
    【云计算】k8s相关资料
  • 原文地址:https://www.cnblogs.com/ldqwyl/p/2023067.html
Copyright © 2020-2023  润新知