xhedgepigx
xhedgepigx

Reputation: 350

Silverlight TextBlock not binding to MVVM, what have I missed?

MainPage.xaml
<TextBlock Text="{Binding Pathname, Source={StaticResource ViewModel}, Mode=OneWay}" />

App.xaml

<ResourceDictionary>
     <vm:InspectViewModel x:Key="ViewModel" />
</ResourceDictionary>

ViewModel

private string _pathname = null;
public string Pathname
{
    get { return _pathname; }
    set
    {
        if (_pathname != value)
        {
            _pathname = value;
            RaisePropertyChanged("Pathname");
        }
    }
}

public void UpdatePathname(string path)
{
    Pathname = path;
}

MainPage CodeBehind

private void lazyNavTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)  
{          
    InspectViewModel vm = new InspectViewModel();        
    var path = view.GetPath().ToArray();
    string pathname = null;
    // to figure out what the pathname is
    for (int i = 0; i < path.Count(); i++)
    {
        TreeList treeItem = (TreeList)path[i].Key;
        if (i == path.Count()-1)
            pathname = pathname + treeItem.Name;
        else
            pathname = pathname + treeItem.Name + " : ";
    }
    vm.UpdatePathname(pathname);
}

The bound TextBlock shows nothing, nada, zip. The pathname shource is changing correctly but nothing seems to happen when I fire the INotifyPropertyChanged event on change.

I am sure I'm missing something really obvious but I can't figure out what!

Upvotes: 0

Views: 159

Answers (3)

Joachim Isaksson
Joachim Isaksson

Reputation: 180887

Looks like you just missed the Path in your binding, try;

Text="{Binding Path=Pathname, Source={StaticResource ViewModel}, Mode=OneWay}"

EDIT: Apparently this was not the problem, but keeping this answer since xhedgepigx provided a useful link as a comment below.

Upvotes: 0

laszlokiss88
laszlokiss88

Reputation: 4071

It's because you create an instance from your viewmodel every times in the lazyNavTree_SelectedItemChanged. You should use only one.

Upvotes: 2

max
max

Reputation: 34407

You are creating 2 instances of your ViewModel:

  • in App.xaml (in app resources, this is the instance which is bound to)
  • in MainPage code-behind (InspectViewModel vm = new InspectViewModel(), this is the modified instance)

You should use single instance of you ViewModel, for example,

var vm = (InspectViewModel)Application.Current.Resources["ViewModel"];

instead of creating it in MainPage code-behind.

Upvotes: 4

Related Questions