Skip to content

Commit

Permalink
Set up a WPF component for a text box with a placeholder.
Browse files Browse the repository at this point in the history
  • Loading branch information
MeltyPlayer committed May 10, 2024
1 parent 412c9ef commit b56afdf
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<UserControl x:Class="uni.src.ui.wpf.common.TextBoxWithPlaceholder"
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"
xmlns:local="clr-namespace:uni.src.ui.wpf.common"
mc:Ignorable="d"
d:DesignHeight="24"
d:DesignWidth="200">
<UserControl.DataContext>
<local:TextBoxWithPlaceholderViewModel />
</UserControl.DataContext>

<Grid>
<TextBox x:Name="impl_"
TextChanged="TextChanged_" />
<Label x:Name="placeholderLabel_"
Content="{Binding Placeholder }"
Background="Transparent"
Opacity="0.5"
IsHitTestVisible="False" />
</Grid>
</UserControl>
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows;

namespace uni.src.ui.wpf.common {
/// <summary>
/// Interaction logic for WatermarkTextBox.xaml
/// </summary>
public partial class TextBoxWithPlaceholder : UserControl {
private readonly TextBoxWithPlaceholderViewModel viewModel_;

public TextBoxWithPlaceholder(TextBoxWithPlaceholderViewModel viewModel) {
InitializeComponent();
this.viewModel_ = viewModel;
}

public string Placeholder {
get => this.viewModel_.Placeholder;
set => this.viewModel_.Placeholder = value;
}

private void TextChanged_(object sender, TextChangedEventArgs args)
=> this.placeholderLabel_.Visibility
= this.impl_.Text != ""
? Visibility.Hidden
: Visibility.Visible;
}

public class TextBoxWithPlaceholderViewModel : INotifyPropertyChanged {
private string placeholder_ = "Search...";
public event PropertyChangedEventHandler? PropertyChanged;

public string Placeholder {
get => this.placeholder_;
set {
this.placeholder_ = value;
this.PropertyChanged?.Invoke(
this,
new PropertyChangedEventArgs(nameof(Placeholder)));
}
}
}
}

0 comments on commit b56afdf

Please sign in to comment.