2016-09-03 37 views
1

我的应用程序中有2个ViewModel。第一个(FirstPageViewModel)负责在View中的文本框中显示的数据。其他视图模型(NavigationViewModel)负责我的页之间以及在改变的TextBlocks值导航:在不同的类中实现INotifyPropertyChanged

<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(=按钮点击)来更改的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”包含相同的实施和套文本框的值:

static int _roundCounter = 1; 
public TextBlockSetter _helloWorld; 

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

    } 

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

有人知道如何正确实施这些更改吗?我的想法是在TextView应该更改时,将NavigationViewModel中的参考引用到FirstPageViewModel。但不幸的是,我的想法没有得到很好的解决。

回答

0

我不完全理解,但,那只是使用一个视图模型 并定义在viewmodel.Therefore屏幕属性,你可以设置 该属性,然后在属性更改事件导航。

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 
     } 
    } 

绑定屏幕名财产在你想怎么视图模型在viewmodel.Then变化propertt属性。

+0

定义屏幕属性是什么意思? – pacours

+0

我得出结论,我应该有2个ViewModels,因为有更多的页面可以像第一个那样导航和传递信息。将所有内容放在一个ViewModel中会使得难以跟踪所有的事情。 – pacours

+0

我并不是说你可以把一切都放在一个viewmodel.every页面有默认导航viewmodel,你可以为你的值定义不同的viewmodels。 – FreeMan

相关问题