• WPF绑定基础


    1、

    XAML:<TextBox Name="textbox1"></TextBox>

    cs:

        public class Customer
        {
            public string Name { get;set;}
        }

               Customer customer = new Customer()
                {
                    Name = "Zhangjinshan"
                };
                Binding bind = new Binding();
                bind.Source = customer;

                bind.Path = new PropertyPath("Name");
                textbox1.SetBinding(TextBox.TextProperty, bind);

    2、

    XAML: <TextBox Name="textbox1" Text="{Binding Path=Name}"></TextBox>

    cs:

               Customer customer = new Customer()
                {
                    Name = "Zhangjinshan"
                };
                textbox1.DataContext = customer;

     

    3、

    XAML:

       <Window.Resources>
            <my:Customer x:Key="mycustomer" Name="ZhangJinshan"/>
        </Window.Resources>
        <StackPanel>
            <StackPanel.DataContext>
                <StaticResource ResourceKey="mycustomer"/>
            </StackPanel.DataContext>
            <TextBox Name="textbox1" Text="{Binding Path=Name}"/>
        </StackPanel>

     

    4、

    <Window.Resources>
            <my:Customer x:Key="mycustomer" Name="Zhangjinshan"/>
        </Window.Resources>
        <StackPanel>
            <TextBox Name="textbox1" Text="{Binding Path=Name, Source={StaticResource ResourceKey=mycustomer}}"/>
        </StackPanel>

     

     

    有一个问题,就是很多地方都写可以这样绑定:

    <TextBox DataContext="{Binding ElementName=customer}" Text="{Binding Path=Name}"/>

     可我怎么试都不行,可能是我理解有误:代码如下:

    XAML:

    <TextBox DataContext="{Binding ElementName=customer}" Text="{Binding Path=Name}"/>

    cs:

    Customer customer = new Customer()
                {
                    Name = "Zhangjinshan"
                };

    请高人指点。。。。

  • 相关阅读:
    js 生成随机数
    解决微信浏览器无法使用reload()刷新页面
    js 去除左右空格
    小程序开发入门-第一天
    我的第一个JSP——动态web
    2019-3-6 复制粘贴
    2019-2-19 异常练习
    2019-1-19 object祖宗类的equals重写
    2019-1-15 课堂笔记
    2019-1-15 课后作业
  • 原文地址:https://www.cnblogs.com/KimhillZhang/p/2417388.html
Copyright © 2020-2023  润新知