我下面的代碼在我的WPF App.xaml.cs文件:問題與app.xaml.cs到MainViewmodel通信
void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
var mainVM = MainWindowViewModel.Instance;
mainVM.DisplayMessage = string.Format("Something went wrong and it has been logged...If the problem persists, please contact {0}.", mainVM.NotificationsReceiver);
mainVM.DisplayMessageForegroundColor = "Red";
e.Handled = true;
}
MainWindowViewModel.cs
public string DisplayMessage
{
get
{
return m_displayMessage;
}
set
{
m_displayMessage = value;
OnPropertyChanged("DisplayMessage");
}
}
public string DisplayMessageForegroundColor
{
get
{
return m_displayMessageForegroundColor;
}
set
{
m_displayMessageForegroundColor = value;
OnPropertyChanged("DisplayMessageForegroundColor");
}
}
MainWindow.xaml
<Label Content="{Binding DisplayMessage}" Foreground="{Binding DisplayMessageForegroundColor}" Grid.Column="1" HorizontalAlignment="Left" Height="33" Margin="14,660,0,0" Grid.Row="1"
VerticalAlignment="Top" Width="693" Grid.ColumnSpan="3"/>
但是,這似乎並沒有工作。雖然在app.xaml.cs中的方法被調用,我沒有看到顯示錯誤m在UI上發送消息。請問這裏有什麼不對嗎? (我可以在MainWindowViewModel中設置DisplayMessage和DisplayMessageForegroundColor屬性時看到消息)。
請指教。
感謝。
我猜MainWindowViewModel.Instance不是綁定到視圖的視圖模型的實例。 – ibebbs
向我們展示如何將'MainWindowViewModel.Instance'賦值給'MainWindow.DataContext'。這可能是問題所在。 @ibebbs幾乎肯定是正確的。 –
你好...我在我的MainWindow.xaml文件中設置上下文---> ....這就是你需要嗎?謝謝。 –