Communication control property from internal control
I have a control that contains another control. InnerControl contains some property like ButtonVisibility. Simplified InnerControl code sample below
public class InnerControl : ControlBase
{
//...
public Visibility ButtonVisibility
{
get { return (Visibility)GetValue(ButtonVisibility); }
set { SetValue(ButtonVisibility, value); }
}
public static readonly DependencyProperty ButtonVisibility =
DependencyProperty.Register(
"ButtonVisibility",
typeof (Visibility),
typeof (InnerControl),
new PropertyMetadata(Visibility.Collapsed));
}
This is the MainControl code which contains the InnerControl as a dependency property
public class MainControl : ControlBase
{
//...
public InnerControl MyInner
{
get { return (InnerControl) GetValue(MyInnerProperty); }
set { SetValue(MyInnerProperty, value); }
}
public static readonly DependencyProperty MyInnerProperty =
DependencyProperty.Register(
"MyInner",
typeof (InnerControl),
typeof (MainControl),
new PropertyMetadata(null, OnMyInnerPropertyChanged));
private static void OnMyInnerPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//...
}
}
I have two different templates for these controls in Generic.xaml
<Style TargetType="local:InnerControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:InnerControl">
<Grid x:Name="ContainerGrid">
<!-- some markup -->
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="local:MainControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MainControl">
<Grid x:Name="RootGrid">
<Button x:Name="MyButton" Visibility="{TemplateBinding ???}"/>
<ContentControl x:Name="MyInnerControl" Content="{TemplateBinding MyInner}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This is how I can use these controls
<controls:MainControl>
<controls:MainControl.MyInner>
<controls:InnerControl ButtonVisibility="Visible">
<!-- some markup -->
</controls:InnerControl>
</controls:MainControl.MyInner>
<!-- some markup -->
</controls:MainControl>
I need to change the state of mine MainControl
after clicking a button. Therefore, it is in the template MainControl
.
So, can any body give me advice on how to link ButtonVisibility
from MyInner
with MyButton
to MainControl
?
source to share
As @james mentioned, you will have to use a RelativeSource to bind to TemplatedParent or any type in the visual tree by specifying the type of the type:
<Button x:Name="MyButton" Content="MyButton"
Visibility="{Binding Path=MyInner.ButtonVisibility,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type controls:MainControl}}}"/>
source to share