在不同的类中实现INotifyPropertyChanged

时间:2016-09-03 13:17:33

标签: c# mvvm

我的应用程序中有2个ViewModel。第一个(FirstPageViewModel)负责在我的View中的TextBox中显示的数据。另一个ViewModel(NavigationViewModel)负责我的页面之间的导航和更改TextBlocks的值:

<StackPanel>
<Button Content="SecondPage" 
        DataContext="{Binding Source={StaticResource NavigationVM}}" /// reference to App.xaml
        Command="{Binding NavigationCommand}" 
        CommandParameter="SecondPage" />
<Grid  DataContext="{Binding Source={StaticResource FirstPageViewModel}}">
  <TextBlock  Text="{Binding helloWorld.Counter, UpdateSourceTrigger=PropertyChanged}"/>
  <TextBlock  Text="{Binding helloWorld.Message, UpdateSourceTrigger=PropertyChanged}"/>
    ...
</Grid>

现在导航工作正常。但是,如果我尝试使用“NavigationViewModel”中的NavigationCommand(= Button Click)更改TextBlocks中的值,则没有任何更改: (TextBlockSetter实现INotifyPropertychanged)

public TextBlockSetter _helloWorld;


    public NavigationViewModel()
    {

        _helloWorld = new TextBlockSetter();

    }

    public TextBlockSetter helloWorld
    {
        get
        {
            return _helloWorld;
        }
        set
        {
            _helloWorld = value;
        }
    }
 private void navigationCommand(object destination)
{
  switch (destination.ToString())
  {
    case "SecondPage":
      {

         ... ///Code for page Navigation

        helloWorld.Counter++;
        helloWorld.Message = "done";
        break;
      }
  }
}

“FirstPageViewModel”包含相同的实现并设置TextBoxes的值:

static int _roundCounter = 1;
public TextBlockSetter _helloWorld;

    public FirstPageViewModel()
    {
        helloWorld.Counter = _roundCounter;
        _helloWorld = new TextBlockSetter();

    }

    public TextBlockSetter helloWorld
    {
        get
        {
            return _helloWorld;
        }
        set
        {
            _helloWorld = value;
        }
    }

有人知道如何正确实施这些更改吗?我的想法是在NavigationboxModel中引用FirstPageViewModel,当文本框应该被更改时。但不幸的是,我的想法都没有成功。

1 个答案:

答案 0 :(得分:0)

我不完全理解,但是,只使用一个视图模型怎么样? 并在该viewmodel中定义一个屏幕属性。因此,您可以设置 该属性然后在属性更改事件中导航。

public static readonly DependencyProperty ScreenNameProperty =
        DependencyProperty.Register("ScreenName", typeof(String),
        typeof(ContentControl), new FrameworkPropertyMetadata("screen_1", new PropertyChangedCallback(ScreenNameChanged)));

    public String ScreenName
    {
        get { return (String)GetValue(ScreenNameProperty); }
        set { SetValue(ScreenNameProperty, value); }
    }

    private static void ScreenNameChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
    {
        ContentControl originator = dependencyObject as ContentControl;
        if (originator != null)
        {
            // navigate here
        }
    }

将ScreenName属性绑定到viewmodel中的属性。然后在viewmodel中更改属性的方式。