XAML 学习(1)

来源:互联网 发布:sql group by 取多列 编辑:程序博客网 时间:2024/05/18 01:56

1.普通的写法

<Canvas>
      <TextBox Name="txtShow" Text="Hello" />
      <TextBlock Canvas.Top="25">
        <TextBlock.Text>
          <Binding ElementName="txtShow" Path="Text" />
        </TextBlock.Text>
      </TextBlock>
   </Canvas> 

2.简化的写法.

<Canvas>
        <TextBox Name="txtShow" Text="Hello" />
        <TextBlock Canvas.Top="25"
           Text="{Binding ElementName=txtShow, Path=Text}" />
      </Canvas> 

ElementName 属性(它用于绑定到一个控件),而不是使用 Source 属性。

3.NET 对象绑定:
<Window x:Class="WindowsApp2.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:c="clr-namespace:BindNonTextProperty"
    Title="WindowsApp2" Height="300" Width="300"
    >
    <Grid>
      <Grid.Resources>
        <c:MyData x:Key="MyDataSource"/>
      </Grid.Resources>
     
      <Grid.DataContext>
        <Binding Source="{StaticResource MyDataSource}"/>
      </Grid.DataContext>
      <Button Background="{Binding Path=ColorName}" Width="150" Height="30">I am bound to Green!</Button>
      <Button Background="{Binding Source={StaticResource MyDataSource},Path=ColorNameT}" Width="20" Height="60">Red!</Button>
     
    </Grid>
</Window>

类文件

using System;

namespace BindNonTextProperty
{
    public partial class MyData
    {
        private string _data = "Green";

        public string ColorName
        {
            get
            {
                return _data;
            }
        }

        public string ColorNameT
        {
            get
            {
                return "Red";
            }
        }
    }
}

 

原创粉丝点击