Search code examples
wpfmvvmstring-formattingmultibinding

How to avoid default text in textbox?


I have a textbox, which uses multi-binding usingStringFormat...as shown below. But it displays the default value as {DependencyProperty.UnsetValue},{DependencyProperty.UnsetValue}

How to avoid this ?

<StackPanel Orientation="Horizontal">
                    <TextBlock Width="70" Text="Name:" Margin="5,2,2,2"></TextBlock>
                    <TextBox Width="160" DataContext="{Binding }" IsReadOnly="True" Margin="2">
                        <TextBox.Text>
                            <MultiBinding StringFormat="{}{0},{1}">
                                <Binding Path="LastName"/>
                                <Binding Path="FirstName"/>
                            </MultiBinding>
                        </TextBox.Text>
                    </TextBox>
</StackPanel>

Please help me.


Solution

  • Something is wrong with the object you are binding to. I just created an application from scratch with a Person class that inherits from DependencyObject. I left the first and last name properties unset and I did not see DependencyProperty.UnsetValue, but rather a blank TextBox with just a comma in it.

    (In general, you shouldn't use dependency properties on your business objects anyway. Stick to INotifyPropertyChanged and save yourself a ton of headaches.)

    Post the code to your bound object and maybe I can spot the issue.

    public class Person : DependencyObject
    {
    
        public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register("FirstName", typeof(string), typeof(Person), new FrameworkPropertyMetadata());
    
        public string FirstName {
            get { return (string)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }
    
        public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register("LastName", typeof(string), typeof(Person), new FrameworkPropertyMetadata());
    
        public string LastName {
            get { return (string)GetValue(LastNameProperty); }
            set { SetValue(LastNameProperty, value); }
        }
    
    }
    

    -

    <TextBox IsReadOnly="True">
        <TextBox.Text>
            <MultiBinding StringFormat="{}{1}, {0}">
                <Binding Path="FirstName" />
                <Binding Path="LastName" />
            </MultiBinding>
        </TextBox.Text>
    </TextBox>
    

    -

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
        }
    
        private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            var p = new Person();
            //p.FirstName = "Josh";
            //p.LastName = "Einstein";          
            DataContext = p;
        }
    }