Проблема привязки в UserControl - PullRequest
0 голосов
/ 21 марта 2019

Я пытаюсь достичь чего-то, что должно быть довольно простым, но я застрял.

Вот что я пытаюсь сделать: UserControl, который является просто значком FontAwesome перед рамкой.

Здесь xaml моего UC

<UserControl
x:Class="Project.Views.UC.UC_CircledIcons"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Project.Views.UC"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:fa="using:FontAwesome5.UWP"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignHeight="200"
d:DesignWidth="200">
<Border Style="{StaticResource BorderStyle1}"  Height="{Binding Height}" Width="{Binding Width}" BorderBrush="{Binding MyColor}" VerticalAlignment="Center" HorizontalAlignment="Center">
    <fa:FontAwesome Foreground="{Binding MyColor}" Icon="{Binding MyIcon}" Height="{Binding Height}" Width="{Binding Width}" FontSize="{Binding MyFontSize}" VerticalAlignment="Center" HorizontalAlignment="Center"></fa:FontAwesome>
</Border>

Вот код cs моего UC:

namespace Project.Views.UC
{
    public sealed partial class UC_CircledIcons : UserControl
    {
        public UC_CircledIcons()
        {
            this.InitializeComponent();
            this.Height = 200;
            this.Width = 200;
        }

        /// <summary>
        /// Le font size de l'icon est égal à 2.6 fois sa hauteur
        /// </summary>
        public double MyFontSize
        {
            get
            {
                return (double)GetValue(HeightProperty) / 2.6;
            }
        }

        /// <summary>
        /// Pour setter l'icone FontAwesome du composant via l'enum
        /// </summary>
        public static readonly DependencyProperty IconProperty = DependencyProperty.Register("MyIcon", typeof(EFontAwesomeIcon), typeof(UC_CircledIcons), new PropertyMetadata(default(EFontAwesomeIcon)));
        public EFontAwesomeIcon MyIcon
        {
            get
            {
                return (EFontAwesomeIcon)GetValue(IconProperty);
            }
            set
            {
                SetValue(IconProperty, value);
            }
        }

        /// <summary>
        /// Pour setter la color du border et de l'icone en même temps
        /// </summary>
        public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("MyColor", typeof(string), typeof(UC_CircledIcons), new PropertyMetadata(default(string)));
        public string MyColor
        {
            get {
                return (string)GetValue(ColorProperty);
            }
            set {
                SetValue(ColorProperty, value);
            }
        }
    }
}

Это работает нормально, если я статически использую свои UserControls на своей странице xaml следующим образом:

<uc:UC_CircledIcons MyColor="#321654" MyIcon="Solid_Check"></uc:UC_CircledIcons>

Но я пытаюсь динамически установить цвет и значок этого UC. Поэтому я хочу использовать привязку для достижения этой цели. Что-то вроде:

<uc:UC_CircledIcons MyColor="{Binding MainIconColor}" MyIcon="{Binding MainIcon}"></uc:UC_CircledIcons>

Как я делаю с любым содержимым Textblock, связываясь с любым свойством моей ViewModel. Но с моим UserControl это не работает. В окнах вывода я вижу ошибку привязки:

Ошибка: ошибка пути BindingExpression: свойство 'MainIcon' не найдено в 'Project.Views.UC.UC_CircledIcons'. BindingExpression: Path = 'MainIcon' DataItem = 'Project.Views.UC.UC_CircledIcons'; целевой элемент - Project.Views.UC.UC_CircledIcons (Name = 'null'); Свойство target - MyIcon (тип EFontAwesomeIcon)

И я считаю, что это вызвано строкой:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

В коде моего UserControl. Похоже, что xaml ищет свойство с именем MainIcon в определении моего USerControl или это свойство является частью моей ViewModel.

Где я что-то упустил? Есть ли способ добиться того, что я пытаюсь сделать? Большое спасибо за помощь.

1 Ответ

1 голос
/ 21 марта 2019

Замените DataContext="{Binding RelativeSource={RelativeSource Self}}" на Name="uc" и свяжите со свойствами, используя ElementName:

<Border ... BorderBrush="{Binding MyColor, ElementName=uc}" ... />

Тогда UserControl должен наследовать его DataContext, как и ожидалось, но вы все равно сможете привязаться к свойствам самого элемента управления в его разметке XAML.

...