UWP - не удалось присвоить свойству «Windows.UI.Xaml.Controls.Primitives.Selector.SelectedIndex» ошибку в шаблонном элементе управления - PullRequest
0 голосов
/ 02 октября 2019

Шаблонное управление моим приложением UWP приводит к сбою приложения при запуске в Windows 10 version-1803. Он отлично работает в более поздних версиях.

Я разделил элемент управления в новом проекте и встроил его в ПК с Windows 10 V 1803. Я получаю эту ошибку: Не удалось присвоить свойству 'Windows.UI.Xaml.Controls.Primitives.Selector.SelectedIndex '

Вот единственный стиль в Generic.xaml :

<Style TargetType="local:PopupButton" >
    <Setter Property="Background" Value="{ThemeResource AppBarBackground}"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="Padding" Value="8 4 8 4"/>
    <Setter Property="IsItemClickEnabled" Value="True"/>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:PopupButton">
                <Grid 
                    x:Name="RootGrid"
                    Background="{TemplateBinding Background}" 
                    BorderThickness="{TemplateBinding BorderThickness}" 
                    BorderBrush="{TemplateBinding BorderBrush}" 
                    HorizontalAlignment="{TemplateBinding HorizontalAlignment}"
                    VerticalAlignment="{TemplateBinding VerticalAlignment}">

                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="PointerOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackground}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Selected">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemAccentColor}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>


                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition Height="8"/>
                    </Grid.RowDefinitions>

                    <ContentPresenter 
                        HorizontalAlignment="Stretch"
                        Content="{TemplateBinding Content}"
                        Padding="{TemplateBinding Padding}"/>
                    <ContentPresenter 
                        x:Name="OptionBtn" 
                        VerticalAlignment="Stretch"
                        Grid.Row="1">
                        <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE011;" FontSize="10"/>
                    </ContentPresenter>

                    <Popup 
                        Grid.ColumnSpan="2" 
                        x:Name="Popup" 
                        IsLightDismissEnabled="True">

                        <Popup.ChildTransitions>
                            <TransitionCollection>
                                <EntranceThemeTransition FromVerticalOffset="-10"/>
                            </TransitionCollection>
                        </Popup.ChildTransitions>

                        <Border x:Name="PopupBorder" 
                                Background="{ThemeResource ComboBoxDropDownBackground}" 
                                HorizontalAlignment="Stretch" >
                            <ScrollViewer x:Name="ScrollViewer" 
                                          AutomationProperties.AccessibilityView="Raw" 
                                          Foreground="{ThemeResource ComboBoxDropDownForeground}"  
                                          VerticalScrollBarVisibility="Hidden">
                                <ItemsPresenter x:Name="Presenter"/>
                            </ScrollViewer>
                        </Border>
                    </Popup>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

И его код позадиочень просто:

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;

namespace UITest
{
    public sealed class PopupButton : ListViewBase
    {
        public bool IsSelected
        {
            get { return (bool)GetValue(IsSelectedProperty); }
            set { SetValue(IsSelectedProperty, value); }
        }

        public static readonly DependencyProperty IsSelectedProperty =
            DependencyProperty.Register("IsSelected", typeof(bool), typeof(PopupButton), new PropertyMetadata(false));


        public object Content
        {
            get { return (object)GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }

        public static readonly DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(object), typeof(PopupButton), null);


        private Popup OptionsPopup;

        public PopupButton()
        {
            this.DefaultStyleKey = typeof(PopupButton);
        }

        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            OptionsPopup = GetTemplateChild("Popup") as Popup;

            PointerEntered += ToggleBtn_PointerEntered;
            PointerPressed += ToggleBtn_PointerPressed;
            PointerExited += SplitToggleButton_PointerExited;
            ItemClick += PopupButton_ItemClick;
            RegisterPropertyChangedCallback(IsSelectedProperty, IsSelectedChanged);
        }

        private void PopupButton_ItemClick(object sender, ItemClickEventArgs e)
        {
            OptionsPopup.IsOpen = false;
        }

        private void IsSelectedChanged(DependencyObject sender, DependencyProperty dp)
        {
            VisualStateManager.GoToState(this, "Selected", false);
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ListViewItem();
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            if (!(element is ListViewItem litem))
                return;
            litem.MinHeight = 25;
        }

        private void ToggleBtn_PointerEntered(object sender, PointerRoutedEventArgs e)
        {
            if (!IsSelected)
                VisualStateManager.GoToState(this, "PointerOver", false);
        }

        private void SplitToggleButton_PointerExited(object sender, PointerRoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, IsSelected ? "Selected" : "Normal", false);

        }

        private void ToggleBtn_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            if (IsSelected)
                OptionsPopup.IsOpen = true;
            else IsSelected = true;
        }
    }
}

И MainPage.xaml :

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

    <Grid>
        <local:PopupButton Content="Hello world!" SelectedIndex="0">
            <x:String>item 1</x:String>
            <x:String>item 2</x:String>
            <x:String>item 3</x:String>
        </local:PopupButton>
    </Grid>
</Page>

Я заметил, что если я удаляю деталь SelectedIndex="0", то она работает нормально. Я не понимаю, в чем здесь проблема с SelectedIndex?

Спасибо.

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