[英]Implement INotifyPropertyChanged in different class
我的應用程序中有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,當文本框應該被更改時。 但不幸的是,我的想法都沒有成功。
我不完全理解,但是,只使用一個viewmodel並在該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中更改屬性的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.