Refreshing Read-Only (Chained) Property in MVVM

Posted by Wonko the Sane on Stack Overflow See other posts from Stack Overflow or by Wonko the Sane
Published on 2010-05-13T14:35:37Z Indexed on 2010/05/13 14:44 UTC
Read the original article Hit count: 278

Filed under:
|
|
|

I'm thinking this should be easy, but I can't seem to figure this out.

Take these properties from an example ViewModel (ObservableViewModel implements INotifyPropertyChanged):

class NameViewModel : ObservableViewModel
{ 
    Boolean mShowFullName = false;
    string mFirstName = "Wonko";
    string mLastName = "DeSane";
    private readonly DelegateCommand mToggleName;

    public NameViewModel()
    {
        mToggleName = new DelegateCommand(() => ShowFullName = !mShowFullName);
    }

    public ICommand ToggleNameCommand
    {
        get { return mToggleName; }
    }

    public Boolean ShowFullName
    {
        get { return mShowFullName; }
        set { SetPropertyValue("ShowFullName", ref mShowFullName, value); }
    }

    public string Name
    {
        get { return (mShowFullName ? this.FullName : this.Initials); }
    }

    public string FullName
    {
        get { return mFirstName + " " + mLastName; }
    }

    public string Initials
    {
        get { return mFirstName.Substring(0, 1) + "." + mLastName.Substring(0, 1) + "."; }
    }
}

The guts of such a [insert your adjective here] View using this ViewModel might look like:

<TextBlock x:Name="txtName"
           Grid.Row="0"
           Text="{Binding Name}" />

<Button x:Name="btnToggleName"
        Command="{Binding ToggleNameCommand}"
        Content="Toggle Name"
        Grid.Row="1" />

The problem I am seeing is when the ToggleNameCommand is fired. The ShowFullName property is properly updated by the command, but the Name binding is never updated in the View.

What am I missing? How can I force the binding to update? Do I need to implement the Name properties as DependencyProperties (and therefore derive from DependencyObject)? Seems a little heavyweight to me, and I'm hoping for a simpler solution.

Thanks, wTs

© Stack Overflow or respective owner

Related posts about wpf

Related posts about mvvm