DotNet关键知识点——WPF篇(五)

1. 数据绑定(Binding)一般配置

常用的绑定的目标(Dependency Object & associated Dependency Property,目标单元):
内容控件目标:object ContentControl.Content
集合控件目标:IEnumerable ItemsControl.ItemSource

绑定器:
Binding ( : BindingBase : MarkupExtension )
Binding binding = new Binding();
binding.ElementName = "WPF控件名称";  / binding.Source = …;
binding.Path = new System.Windows.PropertyPath("路径串");

绑定到源(Object & its Property):
代码动态绑定:BindingExtensionBase FrameworkElement.SetBinding(DependencyProperty dp,  BindingBase binding)  (dp = ContentControl.ContentProperty, ItemsControl.ItemsSourceProperty, …)
             
XAML举例:<Label Content=”{Binding … Path=…}”…> ,  <ListBox ItemsSource=”{Binding … Path=…}"> …
({Binding}中单独出现Path时,“Path=”可以省略)

取消绑定:BindingOperations.ClearBinding(this.Label1, ContentControl.ContentProperty);

使用DataContext:
设置某个单元的FrameworkElement.DataContext属性,为其子单元提供默认的绑定源(Source,ElementName,RelativeSource未设置的Binding),可通过代码和XAML设置。

设置绑定模式:
Default - 采用目标使用的默认方式
OneTime - 仅在程序启动或数据源引用或context变动时候更新,但源本身的值发生变化不触发更新
OneWay - 仅目标因源而改变(实验中发现,有的时候目标因用户修改,例如TextBox,可能不会再接受源的更改)
OneWayToSource - 仅源因目标而改变
TwoWay - 双向变化
源更新:
在上述使用向源反馈更新模式时,设置Binding.UpdateSourceTrigger决定更新的频率:
Explicit - 仅在BindingExpression.UpdateSource()时更新,BindingExpression通过这个形式获取:textBox.GettBindingExpression(TextBox.TextProperty);
LostFocus - 在包含目标的单元失去焦点时更新;
PropertyChanged - 每当目标发生变化时;
Default - 根据目标的特性的默认值。

2. 绑定到Object

用Binding.Source而不是Binding.ElementName,Binding.Path通常忽略。
常用的如画刷设置,以下示例静态对象引用格式:
<Button Background=”{Binding Source={x:Static SystemColors.WindowColor}}” …

另一种应用是绑定到逻辑资源:
在资源中定义某个类型的一个资源<名空间别名:类名 x:Key="对象名称">
绑定:Content=”{Binding Source={ StaticResource 对象名称}, Path=对象属性}"…
其中名空间别名定义: xmlns:别名="clr-namespace:工程代码中的名空间名称[;assembly=库名]"

3. 绑定到WPF控件

ElementName设为组件名字符串;Path设为表示值的组件的变量。

4. 绑定到相对位置

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值