WPF Binding

发布时间 2023-09-30 16:38:22作者: Aatrox1

$\color{#FF0000}{Binding}$

Mode(4种模式)

1。使用twoway方式绑定以后,如果手动更改textbox的值,此时如果通过按钮事件来查看滚动条的value值,就会发现和textbox是一致

2。oneway方式,就是滚动条改变的时候会改变文本框的显示值,但是文本框更改的时候不会更改滚动条的值

3。onetime方法,会发现文本框的值会是滚动条的初始值。而且不会变化

4。onewaytosource。就是文本框更改的时候会改变源的属性。这个时候其实数据源和数据目标已经颠倒过来了

5。default方式,这个方式完全就是根据控件的属性来设置的,比如若是可编辑的(如TextBox.Text属性),Default就采用双向模式;若是只读的(TextBlock.Text)则采用单向模式。

Source

Text="{Binding Source={staticResource str}}"
Text="{Binding Source={staticResource myobj},Path=Message}"
Text="{Binding Source={x:Static local:MyObj.StaticString}}"
Text="{Binding Source={x:Static HorizontalAlignment.Stretch}}"

ElementName

Text="{Binding ElementName=txt,Path=Text}"
说明:
只能绑定可视化树内得对象,无法在toolTip等上实现绑定,可使用以下方式解决
Text="{Binding Source={x:Reference txt},Path=Text}",Reference指在xaml文档内搜索控件实现绑定
'X:Reference 局限性:无法绑定自己的父级

RelativeSource
绑定父级

Text="{Binding RelaticeSource={RelativeSouce Mode=FindAncestor,AncestorType=Window},Path=Name}"
FindAncestor指寻找父级.
Text="{Binding RelaticeSource={RelativeSouce Mode=FindAncestor,AncestorType=Window,AncestorLevel=3},Path=Name}"
AncestorLevel绑定得层级(指父级有嵌套得情况),默认为1

绑定自己

Text="{Binding RelativeSource={RelativeSource Mode=Self},Path=ActualWidth}"

模板内绑定

Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=ActualWidth}"
等价于
Text="{TemplateBinding ActualWidth}"

其他技巧(拓展)
StringFormat

Text="{Binding ElementName=window,Path=top,StringFormat='Top:{0:F3}'}"

MultiBinding
TargetNullValue,FallbackValue,UpdateSourceTrigger
BindingProxy(万能)

<local:BindingProxy x:key="Root" Data="{Binding RelativeSource={RelativeSource AncestorType=Window}}"/>
了解DiscreteObjectKeyFrame