Search code examples
c#wpfwatermarkattached-propertiesmahapps.metro

How to assign both Watermark and a custom property to a TextBox's Text property? (MahApps)


I'm having problems with creating a suitable watermark in my TextBox.

I use MahApps in my project, and as long as I don't bind 'Text' to my custom property, all works fine.

But I need to trace the changes in the TextBox, and so I bind the Text property like this:

<TextBox controls:TextboxHelper.Watermark="Enter text here..." Text="{Binding Path=MyProperty}" />

In this case, the watermark property stops working, the watermark text doesn't disappear when I start typing.

How can it be helped? Thanks!

UPDATE Here's the window of the sample made by har07. In the lower unbound TextBox the watermark works as expected. However, when I try to type smth in the first TextBox, the watermark is still there. enter image description here

UPDATE2 Just in case someone will make the same mistake - appeared I was indeed setting my property in code while initializing the window, and that was the reason the watermark wasn't working. Now, thanks to har07, all is fine.


Solution

  • As I said in comment, there shouldn't be any problem setting watermark along with Text binding. I made simple test using 2 textboxes, one with Text property bound and the other not bound. Both are showing same behavior : watermark text replaced by typed text, and get dimmed upon textbox lost focus.

    //View
    <Controls:MetroWindow x:Class="WpfMahApps.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
            xmlns:local="clr-namespace:WpfMahApps"
            Title="StackOverflow" Height="500" Width="625"
            WindowStartupLocation="CenterScreen">
        <Grid>
            <Grid.DataContext>
                <local:Person/>
            </Grid.DataContext>
            <StackPanel>
                <TextBox Text="{Binding Name}" Controls:TextboxHelper.Watermark="Enter text here...."/>
                <TextBox Controls:TextboxHelper.Watermark="Enter text here too...."/>
            </StackPanel>
        </Grid>
    </Controls:MetroWindow>
    
    //Model (I'm using MvvmLight for implementation of INPC)
    public class Person : ObservableObject
    {
        private string _name = "Default Name";
        public String Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged(() => Name);
            }
        }
    }
    

    Download test project