Фоновое изображение не отображается, если главное окно не активно - PullRequest
0 голосов
/ 28 февраля 2020

У меня есть раздражающая ошибка, которую я не могу понять, и она сводит меня с ума. У меня есть окно со списком в нем, и когда выбран элемент, новое окно открывается с помощью mvvm light, который отображает различные детали, проблема заключается в том, что когда я нажимаю на элемент в моем списке (BrowseGamesView), открывается новое окно (GameDetailsView ) не показывает фоновое изображение, пока я не нажму обратно на BrowseGamesView. Я звоню в API и использую конвертер для создания URL для изображения. Мне нужно, чтобы изображение отображалось при открытии нового окна.

GameDetailsView

Где мне нужно, чтобы фоновое изображение отображалось при открытии окна.

<Window.Resources>
    <vm:GameDetailsViewModel x:Key="vm"/>
    <converters:StringToBackgroundImageConverter x:Key="stringToBackgroundImageConverter"/>
    <converters:StringToImageConverter x:Key="stringToImageConverter"/>
</Window.Resources>
<Grid DataContext="{StaticResource vm}">
    <Grid.Background>
        <ImageBrush ImageSource="{Binding Game.ScreenshotBackground, Converter={StaticResource stringToBackgroundImageConverter}}"/>
    </Grid.Background>
</Grid>

BrowseGamesView

Где хранится список.

<ListBox ItemsSource="{Binding Games}"
             ItemContainerStyle="{DynamicResource ListBoxItemStyle1}"
             SelectedItem="{Binding SelectedGame}"
             Width="480"
             Height="500"
             Grid.Row="4">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Image Source="{Binding cover.image_id, Converter={StaticResource stringToImage}}"
                           Stretch="Fill"
                           Width="100"
                           Height="130"/>
                    <Grid Grid.Column="1">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="310"/>
                                <ColumnDefinition Width="30"/>
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="{Binding name}"
                                       Foreground="White"
                                       FontWeight="Bold"
                                       FontSize="16"
                                       Margin="15 2 0 0"
                                       TextWrapping="Wrap"/>

                            <TextBlock Text="{Binding aggregated_rating, StringFormat={}{0:F0}, Converter={StaticResource nullRatingConverter}}"
                                       Grid.Column="1"
                                       Foreground="{Binding AggregatedRatingColor}"
                                       FontWeight="Bold"
                                       FontSize="16"
                                       HorizontalAlignment="Center"/>
                        </Grid>

                        <ItemsControl Grid.Row="1"
                                      ItemsSource="{Binding DeveloperCompanies}"
                                      Margin="15 2 0 0">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <WrapPanel IsItemsHost="True"/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock x:Name="commaTextBlock" 
                                                   Text=", "
                                                   Foreground="White"/>
                                        <TextBlock Text="{Binding company.name}"
                                                   Foreground="White"
                                                   TextWrapping="Wrap"/>
                                    </StackPanel>
                                    <DataTemplate.Triggers>
                                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource PreviousData}}" Value="{x:Null}">
                                            <Setter Property="Visibility" TargetName="commaTextBlock" Value="Collapsed"/>
                                        </DataTrigger>
                                    </DataTemplate.Triggers>
                                </DataTemplate>

                            </ItemsControl.ItemTemplate>
                        </ItemsControl>

                        <Grid Grid.Row="2"
                              VerticalAlignment="Bottom"
                              Margin="0 0 0 4">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="Release Date:"
                                       Foreground="White"
                                       Margin="15 20 0 0"/>
                            <TextBlock Text="{Binding first_release_date, Converter={StaticResource unixTimestampToDateTimeConverter}}"
                                       Foreground="White"
                                       Margin="10 20 0 0"
                                       Grid.Column="1"/>
                        </Grid>
                    </Grid>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

GameDetailsViewModel

 public class GameDetailsViewModel : INotifyPropertyChanged
{
    private Game game;

    public Game Game
    {
        get { return game; }
        set
        {
            game = value;
            OnPropertyChanged("Game");
        }
    }

    public GameDetailsViewModel()
    {
        Messenger.Default.Register<Game>(this, NotifyMe);
    }

    public void NotifyMe(Game sentGame)
    {
        Game = sentGame;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

BrowseGamesViewModel

 public class BrowseGamesViewModel : ViewModelBase, INotifyPropertyChanged
{
    private string query;
    private Game selectedGame;
    private int gamesCount;
    private Game game;

    public RelayCommand ShowGameDetailsViewCommand { private set; get; }
    public string Query
    {
        get { return query; }
        set
        {
            query = value;
            OnPropertyChanged("Query");
        }
    }
    public Game Game
    {
        get { return game; }
        set
        {
            game = value;
            OnPropertyChanged("Game");
        }
    }

    public Game SelectedGame
    {
        get { return selectedGame; }
        set
        {
            selectedGame = value;
            OnPropertyChanged("SelectedGame");
            GetGameDetails();
            ShowGameDetailsViewCommandExecute();
        }
    }

    public ObservableCollection<Game> Games { get; set; }
    public int GamesCount
    {
        get { return gamesCount; }
        set
        {
            gamesCount = value;
            OnPropertyChanged("GamesCount");
        }
    }
    public SearchGamesCommand SearchGamesCommand { get; set; }

    public BrowseGamesViewModel()
    {
        Games = new ObservableCollection<Game>();
        SearchGamesCommand = new SearchGamesCommand(this);
        ShowGameDetailsViewCommand = new RelayCommand(ShowGameDetailsViewCommandExecute);
    }

    public void ShowGameDetailsViewCommandExecute()
    {
        Messenger.Default.Send(new NotificationMessage("ShowGameDetailsView"));
    }

    private async void GetGameDetails()
    {
        Game = await IGDBHelper.GetGameInformation(SelectedGame.id);
        Messenger.Default.Send(Game);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

BrowseGamesView Код позади

public partial class BrowseGamesView : Window
{
    public BrowseGamesView()
    {
        InitializeComponent();
        Messenger.Default.Register<NotificationMessage>(this, NotificationMessageReceived);
    }

    private void NotificationMessageReceived(NotificationMessage msg)
    {
        if (msg.Notification == "ShowGameDetailsView")
        {
            var view = new GameDetailsView();
            view.Show();
        }
    }
}
...