Search code examples
c#wpfmvvmdata-binding

How change text in label used in UserControl when they have Class?


I make Notofication class look like this

    public class NotificationService : ViewModelBase, INotificationService
{
    public async Task ShowNotification (string content)
    {
        NotificationContent = content;
        ShowHideMenu("showNotificationSB", App.Current.MainWindow.FindName("notification") as StackPanel);
        await Task.Delay(5000);
        ShowHideMenu("hideNotificationSB", App.Current.MainWindow.FindName("notification") as StackPanel);
    }
    public NotificationService()
    {
    }

    private string _notificationContent;
    public string NotificationContent
    {
        get { return _notificationContent; }
        set
        {
            _notificationContent = value;
            OnPropertyChanged();
        }
    }
    private void ShowHideMenu(string Storyboard, StackPanel pnl)
    {
        Storyboard sb = App.Current.MainWindow.Resources[Storyboard] as Storyboard;
        sb.Begin(pnl);
    }
}

and have user control like this

    <Border DataContext="{Binding NotificationService}" Background="#78909C" BorderThickness="2,1,2,5" CornerRadius="0,0,20,20" BorderBrush="#263238">
    <Label HorizontalAlignment="Center" VerticalAlignment="Center" Content="{Binding NotificationContent, UpdateSourceTrigger=PropertyChanged}" Width="Auto" FontSize="12" Foreground="#000000" Margin="10,0,10,0"/>
</Border>

Its in MainWindow.xaml . But app datacontext is bind to MainViewModel. I need to use this notification in Detal view too. When i use ShowNotification in Mainviewmodel its work fine. But when i use this same ShowNotification in other class like detailview, it show me a message from mainviewmodel. How bind this or how use to show message from other class too?


Solution

  • Solved. I move UserControl to MainWindow, and in NotificationService use this

                var notification = App.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
            notification.Noti_Lab.Content = content;