Skip to content

Instantly share code, notes, and snippets.

Export-VM -Name ate-windows-base -Path D:\ate\images
<local:LeftRightLayoutControl>
<Button local:LeftRightLayoutControl.Side="Left">On the left</Button>
<Button local:LeftRightLayoutControl.Side="Right">On the right</Button>
<Button local:LeftRightLayoutControl.Side="Left">On the left again</Button>
</local:LeftRightLayoutControl>
private static void UpdateSide(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var obj = (FrameworkElement)d;
// Finding the LeftRightLayoutControl to which this object belongs to either directly or indirectly.
var parent = LogicalTreeHelper.GetParent(obj);
while (parent != null && parent.GetType() != typeof(LeftRightLayoutControl))
{
parent = LogicalTreeHelper.GetParent(parent);
}
public static readonly DependencyProperty SideProperty = DependencyProperty.RegisterAttached(nameof(Side), typeof(Side), typeof(LeftRightLayoutControl), new PropertyMetadata(Side.None, UpdateSide));
public static Side GetSide(UIElement target)
{
return (Side)target.GetValue(SideProperty);
}
public static void SetSide(UIElement target, Side value)
{
target.SetValue(SideProperty, value);
public enum Side
{
None,
Left,
Right
}
public class LeftRightLayoutControl : StackPanel
{
private Grid _grid;
private StackPanel _left;
private StackPanel _right;
public LeftRightLayoutControl()
{
_grid = new Grid();
_grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
var binding = new Binding(nameof(LabelData)) { Source = this, Mode = BindingMode.OneWay };
BindingOperations.SetBinding(UpdatedLabel, TextBlock.TextProperty, binding);
public static DependencyProperty LabelDataProperty = DependencyProperty.Register(nameof(LabelData), typeof(string), typeof(MainWindow), new PropertyMetadata("Old Label Value"));
public string LabelData
{
get { return (string)GetValue(LabelDataProperty); }
set { SetValue(LabelDataProperty, value); }
}
<Button x:Name="UpdateLabelButton" Grid.Row="1" Grid.Column="1">Update Label</Button>
<TextBlock x:Name="UpdatedLabel" Grid.Row="3" Grid.Column="1">Old Label Value</TextBlock>
<Window x:Class="Z10_BindingFromCode.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>