zoukankan      html  css  js  c++  java
  • WPF学习笔记:(一)数据绑定与DataContext

    前一段半心半意地学习了一下WPF,是从控件入手的,发现巨容易,甚至有些无趣。昨天面试,被问到了很多WPF的特性的东西,直接就傻了。于是乎,还是要去深刻的学习一下WPF。刚刚试了一下数据绑定,几次都没有成功,后来发现是DataContext搞得鬼。

    我暂时有两点结论:

      1、如果没有显式设置上下文,那么数据上下文就是界面;

      例如下边代码,textBox1绑定textBlock2的Text属性的时候,数据上下文就是Grid或者Grid父容器的DataContext,上下文中能用到就是界面元素的属性。

        <Grid>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="123,30,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=MyValue}" />
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="54,77,0,0" Name="textBlock2" Text="Luke" VerticalAlignment="Top" />
        </Grid>
    

      2、可以在任何时候显式设置上下文,但是设置上下文以后绑定才会有效。

      设置方法是ctlId.DataContext = xxx,例如grid1.DataContext = this;

      3、可以在XAML中设置上下文

      在XAML中设置DataContext,有三点要设置:1)引用namespace;2)设置Resources;3)设置DataContext。如下代码所示:

    <Window x:Class="WpfAppDemo1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:c="clr-namespace:WpfAppDemo1"
            Title="MainWindow" Height="350" Width="525">
        <Grid Name="grid1">
            <Grid.Resources>
                <c:MyData x:Key="myData1" />
            </Grid.Resources>
            <Grid.DataContext>
                <Binding Source="{StaticResource myData1}" />
            </Grid.DataContext>
            <TextBox Height="23" HorizontalAlignment="Left" Margin="123,30,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=MyName}" />
        </Grid>

    到目前为止,我只知道这三种设置设置数据上下文的方式。关于数据绑定的内容,我还需要研究:)

  • 相关阅读:
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    Security and Cryptography in Python
    基于分布式锁解决定时任务重复问题
    基于Redis的Setnx实现分布式锁
    基于数据库悲观锁的分布式锁
    使用锁解决电商中的超卖
  • 原文地址:https://www.cnblogs.com/ceachy/p/Binding_DataContext.html
Copyright © 2011-2022 走看看