Skip to content

Instantly share code, notes, and snippets.

@LanceMcCarthy
Created August 4, 2021 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanceMcCarthy/74e8a07766a89729b4645c0b597b3fb8 to your computer and use it in GitHub Desktop.
Save LanceMcCarthy/74e8a07766a89729b4645c0b597b3fb8 to your computer and use it in GitHub Desktop.
A WPF control that stacks a TextBox and a TextBlock togetther
<Window x:Class="YourApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourApp"
Title="MainWindow" Height="350" Width="525">
<Grid>
<local:TextSandwichControl Text="I'm in the textbox"
HeaderText="I'm the label"
Margin="10"/>
</Grid>
</Window>
<UserControl x:Class="YourApp.TextSandwichControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignWidth="200">
<StackPanel>
<TextBlock x:Name="HeaderTextBlock" Text="Header"/>
<TextBox x:Name="TextTextBox" />
</StackPanel>
</UserControl>
using System.Windows;
using System.Windows.Controls;
namespace YourApp
{
public partial class TextSandwichControl : UserControl
{
public TextSandwichControl()
{
InitializeComponent();
}
public static readonly DependencyProperty HeaderTextProperty = DependencyProperty.Register(
"HeaderText", typeof(string), typeof(TextSandwichControl), new PropertyMetadata(default(string), OnHeaderTextPropertyChanged));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text", typeof(string), typeof(TextSandwichControl), new PropertyMetadata(default(string), OnTextPropertyChanged));
public string HeaderText
{
get => (string)GetValue(HeaderTextProperty);
set => SetValue(HeaderTextProperty, value);
}
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextSandwichControl self)
{
if (e.NewValue != null)
{
self.TextTextBox.Text = (string)e.NewValue;
}
}
}
private static void OnHeaderTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TextSandwichControl self)
{
if (e.NewValue != null)
{
self.HeaderTextBlock.Text = (string)e.NewValue;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment