WPF使用代码进行绑定

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

1
2
3
4
5
6
7
8
9
< Window x:Class = "WpfApplication1.Window1"
    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文件中如何进行控件的绑定呢?看下面代码:

1
2
3
4
5
6
7
8
//实例化绑定对象
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就可以了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF ,可以使用后台代码绑定数据,以下是一些常用的绑定方式: 1. 绑定到属性:可以使用 Binding 对象将控件的属性与后台数据源的属性绑定起来。例如: ``` // 假设 DataContext 是一个对象,其有一个名为 Name 的属性 Binding binding = new Binding("Name"); binding.Source = DataContext; textBox.SetBinding(TextBox.TextProperty, binding); ``` 上面的代码将一个 TextBox 的 Text 属性与 DataContext 对象的 Name 属性绑定起来,当 DataContext 对象的 Name 属性发生变化时,TextBox 的文本也会随之更新。 2. 绑定到集合:可以使用 Binding 对象将控件的 ItemsSource 属性与后台数据源的集合绑定起来。例如: ``` // 假设 DataContext 是一个集合,例如 List<string> Binding binding = new Binding(); binding.Source = DataContext; listBox.SetBinding(ListBox.ItemsSourceProperty, binding); ``` 上面的代码将一个 ListBox 的 ItemsSource 属性与 DataContext 对象绑定起来,当 DataContext 对象的集合发生变化时,ListBox 的列表也会随之更新。 3. 绑定到命令:可以使用 CommandBinding 对象将控件的命令与后台的 ICommand 对象绑定起来。例如: ``` // 假设 DataContext 是一个实现了 ICommand 接口的对象 CommandBinding binding = new CommandBinding(ApplicationCommands.Open); binding.Executed += (sender, e) => DataContext.Execute(null); this.CommandBindings.Add(binding); ``` 上面的代码将一个按钮的 Command 属性与 DataContext 对象绑定起来,当按钮被点击时,DataContext 对象的 Execute 方法会被调用。 以上是一些常用的 WPF 后台代码绑定数据的方式,您可以根据具体的需求选择适合的绑定方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值