views:

32

answers:

2

Basically, how do I bind (one-way) to a textbox named txtFullName. Initially, any text in the text box gets cleared/blanked out since ToString returns "". But, when I make changes to FirstName or LastName it does not update the binding against FullName. Any way to do this?

Also, is there any way to bind to a method (not just a field)? That is, set the binding directly to the ToString() method and have it update when FirstName or LastName changes?

Oh, and it would be super awesome if there was some sort of generic way of handling this... like an attribute on the FullName field or an attribute on the ToString method telling it what properties to look for for changes.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace AdvancedDataBinding
{
    public class UserEntity
    {
        static UserEntity()
        {
            FirstNameProperty = DependencyProperty.Register("FirstName", typeof(String), typeof(UserEntity));
            LastNameProperty = DependencyProperty.Register("LastName", typeof(String), typeof(UserEntity));
        }

        public String FirstName
        {
            get { return (String)GetValue(FirstNameProperty); }
            set { SetValue(FirstNameProperty, value); }
        }
        public static readonly DependencyProperty FirstNameProperty;

        public String LastName
        {
            get { return (String)GetValue(LastNameProperty); }
            set { SetValue(LastNameProperty, value); }
        }
        public static readonly DependencyProperty LastNameProperty;

        public String FullName
        {
            get { return ToString(); }
        }

        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
    }
}
+2  A: 

How to bind a textbox to more than one value: Create a MultiValueConverter and use it to bind to both FirstName and LastName.

FullName don't notify when FirstName or LastName changes. In your class, remove all usage of DependencyProperty and instead have the class implement INotifyPropertyChanged. Post the PropertyChanged event for FullName when FirstName or LastName changes. Bind your textbox directly to FullName.

Check out ObjectDataProvider for "binding" to methods.

Out of these answers I suggest you do the second one.

Wallstreet Programmer
Man was about to post the same thing about INotifyPropertyChanged. For a question asked 3 hours ago and only 6 views I thought I had a show at answering it... ;)
aqwert
A: 

You could use a MultiBinding like so...

<TextBlock>
     <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}, {1}">
           <Binding Path="LastName" />
           <Binding Path="FirstName" />
        </MultiBinding>
     </TextBlock.Text>
</TextBlock>
Christopherous 5000