In WPF RelativeSource
binding exposes three properties
to set:
1. Mode: This is an enum
that could have four values:
a. PreviousData(
value=0
): It assigns the previous value of theproperty
to the bound oneb. TemplatedParent(
value=1
): This is used when defining thetemplates
of any control and want to bind to a value/Property of thecontrol
.For example, define
ControlTemplate
:
<ControlTemplate>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</ControlTemplate>
c. Self(
value=2
): When we want to bind from aself
or aproperty
of self.For example: Send checked state of
checkbox
asCommandParameter
while setting theCommand
onCheckBox
<CheckBox ...... CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=IsChecked}" />
d. FindAncestor(
value=3
): When want to bind from a parentcontrol
inVisual Tree
.For example: Bind a
checkbox
inrecords
if agrid
,ifheader
checkbox
is checked
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}, Path=DataContext.IsHeaderChecked, Mode=TwoWay}" />
2. AncestorType: when mode is FindAncestor
then define what type of ancestor
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}
3. AncestorLevel: when mode is FindAncestor
then what level of ancestor (if there are two same type of parent in visual tree
)
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid, AncestorLevel=1}}
Above are all use-cases for
RelativeSource binding
.