图解使用Win8Api进行Metro风格的程序开发四获取和设置登录用户的图片和名字

我们紧接着上篇,这篇将介绍如何使用不同的方式获取和设置登录用户的图片和名字

-----------------------------------我是华丽的分割线-----------------------------------------
今天我们要用Windows.System.UserProfile API获取和设置登录用户的图片和名字

本篇将介绍如下五个方面:
a)获得当前登录用户的显示名
b)获得当前登录用户的FirstName和LastName
c)获得当前登录用户的头像
d)为当前登录用户设置头像
e)注册帐户图片变更的事件

我们的创建的步骤如下:
1)为了组织文件方便,我们先建一个文件夹AccountPictureName
2)向文件夹中添加如下四个文件:
  GetUserDisplayName.xaml,GetUserFirstLastName.xaml,
GetAccountPicture.xaml,SetAccountPictureAndListen.xaml
创建方法请参照前一篇.
3)此时的解决方案结构如下:

4)向我们的DataSource添加导航所需要的信息
  修改我们的SampleDataSource.cs文件中的SampleDataSource类中的代码,
  代码如下: 

View Code

5)我们的导航这样就做好了,效果图:

点击,出现如下图片:

  点击AccountPictureName

6)获得当前登录用户的显示名

  我们使用UserInformation的GetDisplayNameAsync方法

  修改GetUserDisplayName.xaml的xaml:

View Code

  修改后台代码:

View Code
    public sealed partial class GetUserDisplayName : Page
    {
        public GetUserDisplayName()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private async void GetDisplayNameButton_Click(object sender, RoutedEventArgs e)
        {
            string displayName = await UserInformation.GetDisplayNameAsync();
            if (string.IsNullOrEmpty(displayName))
            {
                OutputTextBlock.Text = "No Display Name was returned";
            }
            else
            {
                OutputTextBlock.Text = "Display Name = \"" + displayName + "\"";
            }
        }
    }

7)获得当前登录用户的FirstName和LastName

  我们使用UserInformation.GetFirstNameAsync()和 UserInformation.GetLastNameAsync()

  修改我们的GetUserFirstLastName.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <TextBlock x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >
                Get the first and last name for the current user. This is only available for Microsoft Accounts. An empty string will be returned if not available.
            </TextBlock>
            <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
                <Button x:Name="getFirstNameButton" Content="Get FirstName" Margin="0,0,10,0" Click="GetFirstNameButton_Click"/>
                <Button x:Name="getLastNameButton" Content="Get LastName" Margin="0,0,10,0" Click="GetLastNameButton_Click"/>
            </StackPanel>
        </Grid>
        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/>
        </Grid>
    </Grid>

  修改我们的后台代码:

View Code
    public sealed partial class GetUserFirstLastName : Page
    {
        public GetUserFirstLastName()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private async void GetFirstNameButton_Click(object sender, RoutedEventArgs e)
        {
            //只针对登录名是微软用户
            string firstName = await UserInformation.GetFirstNameAsync();
            if (string.IsNullOrEmpty(firstName))
            {
                OutputTextBlock.Text = "No First Name was returned";
            }
            else
            {
                OutputTextBlock.Text = "First Name = " + firstName;
            }
        }

        private async void GetLastNameButton_Click(object sender, RoutedEventArgs e)
        {
            //只针对登录名是微软用户
            string lastName = await UserInformation.GetLastNameAsync();
            if (string.IsNullOrEmpty(lastName))
            {
                OutputTextBlock.Text = "No Last Name was returned";
            }
            else
            {
                OutputTextBlock.Text = "Last Name = " + lastName;
            }
        }
    }

  效果图:

8)获得当前登录用户的头像

  我们使用UserInformation.GetAccountPicture()

  修改我们的GetAccountPicture.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <TextBlock x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >
                Get the Account Picture for the current user. You can request three different types: small, large and video (dynamic image). If the type that is requested is not available, an empty file is returned.
            </TextBlock>
            <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
                <Button x:Name="getSmallImageButton" Content="Get small image" Margin="0,0,10,0" Click="GetSmallImageButton_Click"/>
                <Button x:Name="getLargeImageButton" Content="Get large image" Margin="0,0,10,0" Click="GetLargeImageButton_Click"/>
                <Button x:Name="getVideoButton" Content="Get video" Margin="0,0,10,0" Click="GetVideoButton_Click"/>
            </StackPanel>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Image x:Name="smallImage" Visibility="Collapsed" AutomationProperties.Name="SmallImage placeholder" Width="96" Height="96"  Margin="0,0,10,0" HorizontalAlignment="Left"/>
            <Image x:Name="largeImage" Visibility="Collapsed" AutomationProperties.Name="LargeImage placeholder" Width="448" Height="448"  Margin="0,0,10,0" HorizontalAlignment="Left"/>
            <MediaElement x:Name="mediaPlayer" Visibility="Collapsed" AutomationProperties.Name="Video placeholder" Width="448" Height="448" Margin="0,0,10,0" HorizontalAlignment="Left"/>
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" Grid.Row="1"/>
        </Grid>
    </Grid>

  修改后台代码:

View Code
    public sealed partial class GetAccountPicture : Page
    {
        public GetAccountPicture()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void ClearText()
        {
            OutputTextBlock.Text = "";
        }

        private async void GetSmallImageButton_Click(object sender, RoutedEventArgs e)
        {
            ClearText();

            // 获得帐户的小头像 96x96 像素
            StorageFile image = UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) as StorageFile;

            if (image != null)
            {
                OutputTextBlock.Text = "SmallImage path = " + image.Path;
                try
                {
                    IRandomAccessStream imageStream = await image.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(imageStream);
                    smallImage.Source = bitmapImage;

                    smallImage.Visibility = Visibility.Visible;
                    largeImage.Visibility = Visibility.Collapsed;
                    mediaPlayer.Visibility = Visibility.Collapsed;
                }
                catch (Exception ex)
                {
                    OutputTextBlock.Text = "Error opening stream: " + ex.ToString();
                }
            }
            else
            {
                OutputTextBlock.Text = "Small Account Picture is not available";
                mediaPlayer.Visibility = Visibility.Collapsed;
                smallImage.Visibility = Visibility.Collapsed;
                largeImage.Visibility = Visibility.Collapsed;
            }
        }

        private async void GetLargeImageButton_Click(object sender, RoutedEventArgs e)
        {
            ClearText();
            // 获得帐户的大头像 448x448 像素
            StorageFile image = UserInformation.GetAccountPicture(AccountPictureKind.LargeImage) as StorageFile;
            if (image != null)
            {
                OutputTextBlock.Text = "LargeImage path = " + image.Path;

                try
                {
                    IRandomAccessStream imageStream = await image.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(imageStream);
                    largeImage.Source = bitmapImage;
                    largeImage.Visibility = Visibility.Visible;
                    smallImage.Visibility = Visibility.Collapsed;
                    mediaPlayer.Visibility = Visibility.Collapsed;
                }
                catch (Exception ex)
                {
                    OutputTextBlock.Text = "Error opening stream: " + ex.ToString();
                }
            }
            else
            {
                OutputTextBlock.Text = "Large Account Picture is not available";
                mediaPlayer.Visibility = Visibility.Collapsed;
                smallImage.Visibility = Visibility.Collapsed;
                largeImage.Visibility = Visibility.Collapsed;
            }
        }

        private async void GetVideoButton_Click(object sender, RoutedEventArgs e)
        {
            ClearText();
            // 获得帐户的视频 448x448 像素
            StorageFile video = UserInformation.GetAccountPicture(AccountPictureKind.Video) as StorageFile;
            if (video != null)
            {
                OutputTextBlock.Text = "Video path = " + video.Path;

                try
                {
                    IRandomAccessStream videoStream = await video.OpenAsync(FileAccessMode.Read);

                    mediaPlayer.SetSource(videoStream, "video/mp4");
                    mediaPlayer.Visibility = Visibility.Visible;
                    smallImage.Visibility = Visibility.Collapsed;
                    largeImage.Visibility = Visibility.Collapsed;
                }
                catch (Exception ex)
                {
                    OutputTextBlock.Text = "Error opening stream: " + ex.ToString();
                }
            }
            else
            {
                OutputTextBlock.Text = "Video is not available";
                mediaPlayer.Visibility = Visibility.Collapsed;
                smallImage.Visibility = Visibility.Collapsed;
                largeImage.Visibility = Visibility.Collapsed;
            }
        }
    }

  效果图:

9)为当前登录用户设置头像,注册帐户图片变更的事件

  我们使用UserInformation.SetAccountPicturesAsync来设置头像,

  使用UserInformation.AccountPictureChanged来注册事件

  修改我们的SetAccountPictureAndListen.xaml的xaml:

View Code
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid x:Name="Input" Grid.Row="0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <TextBlock x:Name="InputTextBlock1"  TextWrapping="Wrap" Grid.Row="0" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >
                Set the Account Picture for the current logon user. The SetAccountPicture method takes three parameters as input: small image, large image, and video. 
                More than one type can be set in the same call, but a small image must be accompanied by a large image and/or video. Pass a null for parameters you don't want to set. 
                A change event can be listened to for Account Picture updates. The images below change by listening to the update.
            </TextBlock>
            <StackPanel Orientation="Horizontal" Margin="0,10,0,0" Grid.Row="1">
                <Button x:Name="setImageButton" Content="Set image" Margin="0,0,10,0" Click="SetImage_Click"/>
                <Button x:Name="setVideoButton"  Content="Set video" Margin="0,0,10,0" Click="SetVideo_Click"/>
            </StackPanel>
        </Grid>

        <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Image x:Name="accountPic" Visibility="Collapsed" AutomationProperties.Name="LargeImage placeholder" Width="448" Height="448"  Margin="0,0,10,0" HorizontalAlignment="Left"/>
            <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" Grid.Row="1"/>
        </Grid>
    </Grid>

  修改我们的后台代码:

View Code
    public sealed partial class SetAccountPictureAndListen : Page
    {
        public SetAccountPictureAndListen()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //添加事件
            UserInformation.AccountPictureChanged += this.PictureChanged;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //移除事件
            UserInformation.AccountPictureChanged -= this.PictureChanged;
        }

        private async void SetImage_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker imagePicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" }
            };

            StorageFile imageFile = await imagePicker.PickSingleFileAsync();
            if (imageFile != null)
            {
                // SetAccountPictureAsync()接受3个storageFile对象来设置的小图像,大图像和视频。                
                //一个小图像,必须伴随着一个大的图像和/或视频。               
                //如果只有一个大的图像,小图像将自动生成。                
                //如果只通过视频,大图像和小将自动生成。                
                //影片必须是可转换的MP4,<=5MB,高度和宽度>= 448像素。
                // Setting the Account Picture will fail if user disallows it in PC Settings.
                //如果在PC设置中不允许, 则设置用户帐户的图片会失败
                SetAccountPictureResult result = await UserInformation.SetAccountPicturesAsync(null, imageFile, null);
                if (result == SetAccountPictureResult.Success)
                {
                    OutputTextBlock.Text = "Account picture was successfully changed.";
                }
                else
                {
                    OutputTextBlock.Text="Account picture could not be changed.";
                    accountPic.Visibility = Visibility.Collapsed;
                }
            }
        }

        private async void SetVideo_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker videoPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.VideosLibrary,
                FileTypeFilter = { ".mp4", ".mpeg", ".wmv", ".mov" }
            };

            StorageFile videoFile = await videoPicker.PickSingleFileAsync();
            if (videoFile != null)
            {
                SetAccountPictureResult result = await UserInformation.SetAccountPicturesAsync(null, null, videoFile);
                if (result == SetAccountPictureResult.Success)
                {
                    OutputTextBlock.Text = "Video account picture was successfully changed.";
                }
                else
                {
                    OutputTextBlock.Text = "Account picture could not be changed.";
                    accountPic.Visibility = Visibility.Collapsed;
                }
            }
        }

        private async void PictureChanged(object sender, object e)
        {
            // 获得帐户的大头像 448x448 像素
            StorageFile image = UserInformation.GetAccountPicture(AccountPictureKind.LargeImage) as StorageFile;
            if (image != null)
            {
                try
                {
                    IRandomAccessStream imageStream = await image.OpenReadAsync();
                    //异步运行事件调度程序,并返回事件调度的结果
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(imageStream);
                        OutputTextBlock.Text = "LargeImage path = " + image.Path;
                        accountPic.Source = bitmapImage;
                        accountPic.Visibility = Visibility.Visible;
                    });
                }
                catch (Exception ex)
                {
                    OutputTextBlock.Text = "Error opening stream: " + ex.ToString();
                }
            }
            else
            {
                await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    OutputTextBlock.Text = "Large Account Picture is not available";
                });
            }
        }
    }

  效果图:

未完待续,敬请期待...

转载请注明出处:http://www.cnblogs.com/refactor/

原文地址:https://www.cnblogs.com/refactor/p/2543306.html