In WPF C#, How can i make a Custom TextBox that has label that acts like 'Hint' in materialdesginfloatinghintTextBox?

Mesh Ka 345 Reputation points
2023-12-05T11:37:07.24+00:00

Hi Everybody, I wanted to Create a Custom Control in WPF C# that is Composed of a MaterialDesignFloatingHintTextBox which 'IsFloating' property is set to 'False' and a Label above the textbox that behaves like a Floating Hint, for the label i wanted it to float above always regarding whether the textbox is empty or not, Also wanted to allow my users to able to change the color of the label, it's size e.t.c and same for the textbox.

In Simple Words it looks like a MaterialDesignFloatingHintTextBox which the hint Property is fixed at the top regardless of whether the textbox is empty or not and at the same time has a hint that is not floating inside the textbox.

I know this needs some StackPanel + MaterialDesignFloatingHintTextBox + a Label at the top, but i am confused, Help!

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,674 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,262 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
765 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 38,256 Reputation points Microsoft Vendor
    2023-12-06T06:26:48.4566667+00:00

    Hi,@Mesh Ka. Welcome to Microsoft Q&A Forum.

    Method 1:

    To create a custom control in WPF composed of a MaterialDesignFloatingHintTextBox and a label behaving like a floating hint, you could create a new UserControl that encapsulates both elements.

    To achieve customization, you can expose dependency properties for the various settings you want to allow users to change.

    FloatingHintTextBoxControl.xaml:

    <UserControl x:Class="MaterialdesignFloatingHintTextBoxDemo.FloatingHintTextBoxControl"
    ...
                 xmlns:local="clr-namespace:MaterialdesignFloatingHintTextBoxDemo"
                   xmlns:materialdesign="http://materialdesigninxaml.net/winfx/xaml/themes"
                 mc:Ignorable="d" 
                 d:DesignHeight="450" d:DesignWidth="800">
        <UserControl.Resources>
                <Style x:Key="NameTextBox" TargetType="TextBox" BasedOn="{StaticResource MaterialDesignFloatingHintTextBox}">
                    <Setter Property="materialdesign:HintAssist.IsFloating" Value="False"/>
                    <Setter Property="materialdesign:ColorZoneAssist.Mode" Value="Dark"/>
                    <Setter Property="materialdesign:HintAssist.HintOpacity" Value="0.40"/>
                    <Setter Property="materialdesign:HintAssist.FontFamily" Value="Century Gothic"/>
                    <Setter Property="Foreground" Value="Yellow"/>
                    <Setter Property="FontSize" Value="20"/>
                </Style>
        </UserControl.Resources>
        <StackPanel>
            <Label x:Name="floatingLabel" 
                   Content="{Binding TextBoxHint, RelativeSource={RelativeSource AncestorType=UserControl, Mode=FindAncestor}}"
                   Foreground="{Binding HintForeground, RelativeSource={RelativeSource AncestorType=UserControl, Mode=FindAncestor}}"
                   VerticalAlignment="Center"    HorizontalAlignment="Left"  RenderTransformOrigin="0.5,0.5">
               
            </Label>
            <TextBox x:Name="textBox"  Style="{StaticResource NameTextBox}"     HorizontalAlignment="Stretch"     VerticalAlignment="Stretch"/>
        </StackPanel>
    </UserControl>
    
    

    FloatingHintTextBoxControl.xaml.cs :

    public partial class FloatingHintTextBoxControl : UserControl
    {
      public FloatingHintTextBoxControl()
      {
        InitializeComponent();
    
      }
      public static readonly DependencyProperty TextBoxHintProperty =
             DependencyProperty.Register("TextBoxHint", typeof(string), typeof(FloatingHintTextBoxControl), new PropertyMetadata("Hint"));
    
      public string TextBoxHint
      {
        get { return (string)GetValue(TextBoxHintProperty); }
        set { SetValue(TextBoxHintProperty, value); }
      }
    
      public static readonly DependencyProperty HintForegroundProperty =
          DependencyProperty.Register("HintForeground", typeof(Brush), typeof(FloatingHintTextBoxControl), new PropertyMetadata(Brushes.Red));
    
      public Brush HintForeground
      {
        get { return (Brush)GetValue(HintForegroundProperty); }
        set { SetValue(HintForegroundProperty, value); }
      }
    
    
    }
    
    

    Method 2:

    To create a custom control in WPF composed of a MaterialDesignFloatingHintTextBox and a label acting as a floating hint, you could derive a new class from Control or ContentControl. You'll then define the visual structure in the control template and expose dependency properties for customization.

    Generic.xaml:

    
    <ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:materialdesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:local="clr-namespace:MaterialdesignFloatingHintTextBoxDemo">
    
    
        <Style TargetType="{x:Type local:CustomHintTextBox}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomHintTextBox}">
                        <StackPanel>
                            
                            <Label Content="{TemplateBinding HintText}"
                                       Foreground="{TemplateBinding HintForeground}"
                                       VerticalAlignment="Stretch" />
                            <TextBox x:Name="textBox"
                                                     HorizontalAlignment="Stretch"
                                                     VerticalAlignment="Center"
                                                     materialdesign:HintAssist.IsFloating="False"
                                                    
                                     materialdesign:ColorZoneAssist.Mode="Dark"
                                     materialdesign:HintAssist.HintOpacity="0.7"
                                     materialdesign:HintAssist.FontFamily="Century Gothic"
                                                     Foreground="{TemplateBinding Foreground}" />
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>
    
    

    CustomHintTextBox:

    
    public class CustomHintTextBox : Control
    {
      static CustomHintTextBox()
      {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomHintTextBox), new FrameworkPropertyMetadata(typeof(CustomHintTextBox)));
      }
      public static readonly DependencyProperty HintTextProperty =
         DependencyProperty.Register("HintText", typeof(string), typeof(CustomHintTextBox), new PropertyMetadata("Hint"));
    
      public string HintText
      {
        get { return (string)GetValue(HintTextProperty); }
        set { SetValue(HintTextProperty, value); }
      }
    
      public static readonly DependencyProperty HintForegroundProperty =
          DependencyProperty.Register("HintForeground", typeof(Brush), typeof(CustomHintTextBox), new PropertyMetadata(Brushes.Red));
    
      public Brush HintForeground
      {
        get { return (Brush)GetValue(HintForegroundProperty); }
        set { SetValue(HintForegroundProperty, value); }
      }
    }
    
    

    Usage:

    enter image description here

    It is recommended to move the resources into App.xaml.

    App.xaml:

    
    <Application x:Class="MaterialdesignFloatingHintTextBoxDemo.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:local="clr-namespace:MaterialdesignFloatingHintTextBoxDemo"
                 StartupUri="MainWindow.xaml">
        <Application.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml"/>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml"/>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Green.xaml"/>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Application.Resources>
    </Application>
    
    

    MainWindow.xaml:

    
    <Grid>
        <Grid.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FF06013F" Offset="1"/>
                <GradientStop Color="#FF040F2E"/>
            </LinearGradientBrush>
        </Grid.Background>
        <StackPanel Margin="30" Orientation="Horizontal" Height="80">
            <local:CustomHintTextBox HintText="Your Hint" Foreground="Red" HintForeground="Gray" />
            
            <local:FloatingHintTextBoxControl TextBoxHint="Enter your text" HintForeground="Pink"/>
        </StackPanel>
    </Grid>
    
    

    The result:

    9


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful