Question

I believe this is possible, but I don't seem to be able to get it to work; here's my view model:

namespace MyApp.ViewModel
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private static MainViewModel _mvm;
        public static MainViewModel MVM()
        {
            if (_mvm == null)
                _mvm = new MainViewModel();

            return _mvm;
        }

        private string _imagePath = @"c:\location\image.png";
        public string ImagePath
        {
            get { return _imagePath; }
            set
            {
               SetProperty<string>(ref _imagePath, value); 
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
        {
            if (Equals(storage, value)) return false;

            storage = value;
            OnPropertyChanged<T>(propertyName);
            return true;
        }

        private void OnPropertyChanged<T>([CallerMemberName]string caller = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(caller));
            }
        }
 ...

Here's my App.xaml:

xmlns:vm="using:MyApp.ViewModel">

<Application.Resources>
    <ResourceDictionary>
        <vm:MainViewModel x:Key="MainViewModel"  />
    </ResourceDictionary>
</Application.Resources>

Here's the binding:

<Page
 ...
    DataContext="{Binding MVM, Source={StaticResource MainViewModel}}">

    <StackPanel Orientation="Horizontal" Margin="20" Grid.Row="0">
        <TextBlock FontSize="30" Margin="10">Image</TextBlock>            
        <TextBox Text="{Binding ImagePath}" Margin="10"/>
    </StackPanel>
...

I don't seem to be able to get the binding to work; what have I missed here? I would expect the field to be populated with the default value, but it isn't; I've put breakpoints in the ViewModel, but it is not breaking.

Was it helpful?

Solution

To me your binding syntax is incorrect. DataContext="{Binding MVM, Source={StaticResource MainViewModel} means you should have a "MVM" PROPERTY in your MainViewModel class. In your case MVM is a method.

Try replacing your MVM method by a property. That might work.

Another way to do it, is to set

DataContext="{StaticResource MainViewModel}"

In that case, the MVM method will be obsolete (I did not try it on WinRT)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top