Изображение не отображается в UserControl - PullRequest
0 голосов
/ 31 января 2019

Я нашел так много ответов на эти вопросы, но, что бы я ни пытался, ничего не получается.

Я пытаюсь создать UserControl в приложении UWP.Пользовательский элемент управления состоит из рамки с изображением и текстовым блоком внутри.Мне удалось заставить текст TextBlock отображаться, но независимо от того, что я делаю, я не могу получить изображение для отображения в UserControl.

Что пыталось сделать до сих пор:

  • Изменение GraphicProperty typeof на Image, ImageSource и Uri.
  • Помещение изображения в рамке в ContentPresenter.
  • Другие вещи, которые я не могу вспомнить в данный момент.

Я не знаю, как заставить это работать.Я знаю, что делал это раньше, но это было несколько лет назад, и я, видимо, запотел, как (или что-то существенное изменилось с UWP, поскольку большая часть моего опыта связана с WPF).

Может кто-нибудь помочь, пожалуйстанайти, где я все испортил?

UserControl XAML:

<UserControl
    x:Class="ShirtSleeves.CardControlxaml"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ShirtSleeves"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Name="CardControl"
    mc:Ignorable="d"
    d:DesignHeight="400"
    d:DesignWidth="300">
    <Grid>
        <Border Margin="0,10" Background="White" BorderBrush="Black" BorderThickness="5" Width="260" Height="352" CornerRadius="20">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Image Source="{Binding ElementName=CardControl, Path=Graphic}" Height="200" Width="200" HorizontalAlignment="Center" VerticalAlignment="Bottom" />
                <TextBlock Text="{Binding ElementName=CardControl, Path=Label}" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,30" Foreground="Black" FontSize="48" FontWeight="Bold" />
            </Grid>
        </Border>

    </Grid>
</UserControl>

UserControl C #:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236

namespace ShirtSleeves
{
    public sealed partial class CardControlxaml : UserControl
    {
        //private TextBlock label;

        public static DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string),
            typeof(CardControlxaml), new PropertyMetadata("Label"));

        public static DependencyProperty GraphicProperty = DependencyProperty.Register("Graphic", typeof(string),
            typeof(CardControlxaml), new PropertyMetadata(null));
        public string Label
        {
            get { return (string)GetValue(LabelProperty); }
            set { SetValue(LabelProperty, value); }
        }

        public string Graphic
        {
            get { return (string)GetValue(GraphicProperty); }
            set { SetValue(GraphicProperty, value); }
        }

        public CardControlxaml()
        {
            this.InitializeComponent();
        }
    }
}

MainPage XAML:

<Page
    x:Class="ShirtSleeves.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ShirtSleeves"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d"
    d:DesignHeight="1200"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid Background="DarkGreen">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="3*" />
        </Grid.ColumnDefinitions>
        <ScrollViewer Grid.Column="0">
            <StackPanel>
                <Border Margin="0,10" Background="White" BorderBrush="Black" BorderThickness="5" Width="260" Height="352" CornerRadius="20">
                    <TextBlock Text="Games" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,30" Foreground="Black" FontSize="48" FontWeight="Bold" />

                </Border>
                <Border Margin="0,10" Background="White" BorderBrush="Black" BorderThickness="5" Width="260" Height="352" CornerRadius="20">
                    <TextBlock Text="Sleeves" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,30" Foreground="Black" FontSize="48" FontWeight="Bold" />
                </Border>
                <local:CardControlxaml Label="Search" Graphic="C:\Users\<username>\source\repos\ShirtSleeves\ShirtSleeves\Images\Rook (Games).png" Foreground="Black" />
                <Image Height="250"  Source="C:\\Users\\<username>\\source\\repos\\ShirtSleeves\\ShirtSleeves\\Images\\Rook (Games).png" HorizontalAlignment="Center" VerticalAlignment="Center" />
            </StackPanel>
        </ScrollViewer>
        <Viewbox Grid.Column="1">
            <Image Source="C:\Users\<username>\source\repos\ShirtSleeves\ShirtSleeves\Images\Rook (Games).png" VerticalAlignment="Top" HorizontalAlignment="Center" />
        </Viewbox>

    </Grid>
</Page>

1 Ответ

0 голосов
/ 01 февраля 2019

UWP не позволяет напрямую обращаться к файлам вне контейнера приложения.Это означает, что вы не можете установить источник изображения следующим образом C:\Users\<username>\source\repos\ShirtSleeves\ShirtSleeves\Images\Rook (Games).png.

. В вашем случае самый простой способ - поместить изображение в папку «Ресурсы» вашего проекта, как показано ниже:

enter image description here

Затем вы можете указать свойство «Графика» следующим образом:

<local:CardControlxaml Label="Search" Graphic="Assets/animals.jpg" Foreground="Black" />

Более подробную информацию см. В Права доступа к файлу .

...