WPF使用代码进行绑定

2010年2月5日 分类: WPF

关于WPF绑定机制,给我们带来了很大的方便,我们都了解在WPF绑定中使用XAML方式可以这样做,代码如下:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <TextBlock Name="txtbShow" Height="21" Margin="47,32,111,0" VerticalAlignment="Top" Text="{Binding ElementName=txtInput,Path=Text}" />
        <TextBox Name="txtInput" Height="23" Margin="47,70,111,0" VerticalAlignment="Top" />
    </Grid>
</Window>

但是如果在cs文件中如何进行控件的绑定呢?看下面代码:

//实例化绑定对象
Binding textBinding = new Binding();
//设置要绑定源控件
textBinding.Source = this.txtInput;
//设置要绑定属性
textBinding.Path = new PropertyPath("Text");
//设置绑定到要绑定的控件
this.txtbShow.SetBinding(TextBlock.TextProperty, textBinding);

从上面代码可以看出,WPF用代码的方式也能很好的进行绑定操作。如果我们要执行双向绑定,或者设置Converter的时候怎么办呢?我们只要设置Binding的这两个属性Binding.Converter,Binding.Mode就可以了。

原创文章,转载请注明: 转载自.NET开发者

本文链接地址: WPF使用代码进行绑定

文章的脚注信息由WordPress的wp-posturl插件自动生成

Related posts:

  1. WPF中的Converter
  2. WPF实现动态换肤功能(一)
  3. WPF无边框透明窗体的缩放
  4. WPF中的拖放(一)
  5. MVVM(Model-View-ViewModel)实例讲解
标签: ,

1条评论 于 “WPF使用代码进行绑定”

  1. 2010年2月7日00:16
    1

    学习了~ 博主学识太强大了

Leave a Comment