如何从另一个页面访问 MainPage.xaml 控件

How to access MainPage.xaml controls from another page

我在 MainPage.xaml 中有一个图像元素,在 SettingsContract1.xaml 中有一个弹出按钮,当单击弹出项目时,文件选择器将打开,我想将它们设置为图像的图像源包含从文件选择器中选择的文件的主页。我如何从 SettingsContract1.xaml

访问图像

MainPage.xaml

中的图片
<Image x:Name="img" HorizontalAlignment="Left" Height="332" VerticalAlignment="Top" Width="778" Margin="349,406,0,0"/>

SettingsContract1.xaml

中的 menuflyout 子
Private Sub chooseFile_Click(sender As Object, e As RoutedEventArgs) Handles chooseFile.Click
    Dim filePicker As FileOpenPicker
    filePicker = New FileOpenPicker()
    filePicker.ViewMode = PickerViewMode.Thumbnail
    filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary
    filePicker.FileTypeFilter.Add(".png")
    Dim file As StorageFile = Await filePicker.PickSingleFileAsync()

    Using filestream As Streams.IRandomAccessStream = Await file.OpenAsync(FileAccessMode.Read)
        Dim bitmapImage As Windows.UI.Xaml.Media.Imaging.BitmapImage = New BitmapImage
        bitmapImage.SetSource(filestream)
        img.Source = bitmapImage 'gives an error
    End Using

End Sub

您可以创建一个映射到 MainPage 的变量,然后访问那里的任何 public 成员表单。

Dim mp = TryCast(Application.Current.RootVisual, MainPage)
If Not mp Is Nothing Then
  mp.img.Source = bitmapImage
End If

找到答案here并将其转换为VB

Private Async Sub chooseFile_Click(sender As Object, e As RoutedEventArgs) Handles chooseFile.Click
    Dim mapImage As Frame = Window.Current.Content
    Dim mainPage As MainPage = mapImage.Content
    Dim filePicker As FileOpenPicker
    filePicker = New FileOpenPicker()
    filePicker.ViewMode = PickerViewMode.Thumbnail
    filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary
    filePicker.FileTypeFilter.Add(".png")
    Dim file As StorageFile = Await filePicker.PickSingleFileAsync()

    Using filestream As Streams.IRandomAccessStream = Await file.OpenAsync(FileAccessMode.Read)
        Dim bitmapImage As Windows.UI.Xaml.Media.Imaging.BitmapImage = New BitmapImage
        bitmapImage.SetSource(filestream)
        mainPage.img.Source = bitmapImage
    End Using

End Sub