Пользовательский контроль UWP DependencyProperty не работает - PullRequest
1 голос
/ 29 апреля 2019

Я изучаю UWP User Control и вижу следующий код:

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

    <StackPanel>
        <local:MyUserControl Username="aaa" Password="bbb" fillcolor="Blue" />
    </StackPanel>
</Page>

Я определил пользовательский элемент управления с тремя свойствами зависимостей: Имя пользователя, Пароль и Цвет заливки. Приведенный ниже код показывает мой пользовательский элемент управления xaml

<UserControl
    x:Name="myctrl"
    x:Class="LearningUWP.MyUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LearningUWP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    >
    <RelativePanel>
        <Rectangle Fill="{Binding fillcolor, ElementName=myctrl}"  x:Name="Rec" Height="100"   RelativePanel.AlignRightWithPanel="True" />
        <TextBlock Text="Username_lbl" RelativePanel.AlignRightWithPanel="True" TextAlignment="Center" RelativePanel.Below="Rec" x:Name="Username_lb" Margin="0,50,0,0" RelativePanel.AlignLeftWithPanel="True" />
        <TextBox x:Name="Username_input" RelativePanel.Below="Username_lb" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" Margin="0,20,0,0" Text="{Binding Username, ElementName=myctrl}"  ></TextBox>
        <TextBlock Text="Password_lbl" x:Name="Password_lb" RelativePanel.AlignRightWithPanel="True" TextAlignment="Center" RelativePanel.Below="Username_input" RelativePanel.AlignLeftWithPanel="True" Margin="0,20,0,0" ></TextBlock>
        <TextBox x:Name="Password_input" RelativePanel.Below="Password_lb" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignLeftWithPanel="True" Margin="0,20,0,0" Text="{Binding Password, ElementName=myctrl}" ></TextBox>
    </RelativePanel>
</UserControl>

и код-позади:

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;
namespace LearningUWP
{
    public sealed partial class MyUserControl : UserControl
    {
        public MyUserControl()
        {
            this.InitializeComponent();
        }
        public string Username
        {
            get { return (string)GetValue(UsernameProperty); }
            set { SetValue(UsernameProperty, value); }
        }
        public static readonly DependencyProperty UsernameProperty =
            DependencyProperty.Register("Username", typeof(string), typeof(MyUserControl), null);
        public string Password
        {
            get { return (string)GetValue(PasswordProperty); }
            set { SetValue(PasswordProperty, value);         }
        }
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.Register("Password", typeof(string), typeof(MyUserControl), null);
        public string fillcolor
        {
            get { return (string)GetValue(fillcolorProperty); }
            set { SetValue(fillcolorProperty, value); }
        }
        public static readonly DependencyProperty fillcolorProperty =
            DependencyProperty.Register("fillcolor", typeof(string), typeof(MyUserControl), null);
    }
}

Имя пользователя и пароль работают так, как я вижу «aaa» и «bbb» на моем экране, но цвет не работает. Как это решить?

Update1

Я изменил свойство fillcolor для следующего кода:

public Brush fillcolor
        {
            get { return (Brush)GetValue(fillcolorProperty); }
            set { SetValue(fillcolorProperty, value); }
        }
        public static readonly DependencyProperty fillcolorProperty =
            DependencyProperty.Register("fillcolor", typeof(Brush), typeof(MyUserControl), null);

Но это все еще не работает.

UPDATE2

Я обновил файл MainPage.xaml, показанный ниже:

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

    <Page.Resources>
        <SolidColorBrush x:Key="MyBlueColor" Color="#0000FF"/>
    </Page.Resources>
    <StackPanel>
        <local:MyUserControl Username="aaa" Password="bbb" fillcolor="{StaticResource MyBlueColor}" />
    </StackPanel>
</Page>

Но это все еще не работает.

1 Ответ

3 голосов
/ 29 апреля 2019

Ваша привязка кажется правильной, ваша проблема в Type вашего свойства 'fillcolor'.Вы связываете это как строку, тогда как вы должны связать это как Brush

 public Brush fillcolor
        {
            get { return (Brush)GetValue(fillcolorProperty); }
            set { SetValue(fillcolorProperty, value); }
        }
 public static readonly DependencyProperty fillcolorProperty =
            DependencyProperty.Register("fillcolor", typeof(Brush), typeof(MyUserControl), null);

Для свойства Fill для правильной работы требуется Brush, как вы можете видеть здесь Shape.Fill

Я забыл упомянуть, что вам не нужно указывать имя элемента в этом случае, так как вы используете свой код как «ViewModel», поэтому код ниже будет делатьтрюк для вас:

<Rectangle Fill="{x:Bind fillcolor}"  x:Name="Rec" Height="100"   RelativePanel.AlignRightWithPanel="True" />

Кроме того, вам необходимо указать Brush в ресурсах вашей страницы в виде сплошной кисти, чтобы вы могли написать:

<Page
    x:Class="LearningUWP.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:LearningUWP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Page.Resources>
     <SolidColorBrush x:Key="MyBlueColor" Color="#0000FF"/> <!-- or Blue -->
    </Page.Resources>
    <StackPanel>
        <local:MyUserControl Username="aaa" Password="bbb" fillcolor="{StaticResource MyBlueColor}" />
    </StackPanel>
</Page>

И, в соответствии с Разница между связыванием и xbind Нам нужно использовать x:Bind Привязка не поддерживает каркасные элементы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...