Скрыть элементы, когда не в фокусе - PullRequest
0 голосов
/ 04 сентября 2018

У меня есть кнопка, которая добавляет TextBox при нажатии, затем пользователь может редактировать содержимое TextBox, нажав на TextBox.

Мне нужно показать изображение (с функцией удаления) ТОЛЬКО, когда TextBox находится в фокусе. т.е. был прослушан.

Изображение должно исчезнуть, когда TextBox потерял фокус. пользователь нажал на другой элемент управления. Кто-нибудь знает, как этого можно достичь?

Вот то, что у меня есть.

    private void Textwriting_Tapped(object sender, TappedRoutedEventArgs e)
    {
        //Set HitTest Visibility
        DragBoundsOverlay.IsHitTestVisible = false;
        emojiCanvas.IsHitTestVisible = false;
        textCanvas.IsHitTestVisible = true;
        inkCanvas.IsHitTestVisible = false;

        //TODO Add Custom Onscreen Keyboard Support

        //Win Onscreen Keyboard Scope - i.e. Number, Text etc
        InputScope scope = new InputScope();
        InputScopeName scopeName = new InputScopeName();
        scopeName.NameValue = InputScopeNameValue.ChatWithoutEmoji;
        scope.Names.Add(scopeName);

        if (AddTextBox == null)
        {
            AddTextBox = new TextBox
            {
                Foreground = new SolidColorBrush(Colors.White),
                Background = new SolidColorBrush(Colors.Transparent),
                BorderBrush = new SolidColorBrush(Colors.Transparent),
                CanDrag = true,
                IsTapEnabled = true,
                PlaceholderText = "Type Text Here...",
                FontSize = 45f,
                AcceptsReturn = true,

                // Win Onscreen Keyboard Settings
                AllowFocusOnInteraction = true,
                PreventKeyboardDisplayOnProgrammaticFocus = false,
                InputScope = scope,

                ManipulationMode = ManipulationModes.All,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center
            };

            //Drag Handlers
            AddTextBox.AddHandler(PointerPressedEvent, new PointerEventHandler(TextManipulation.AddTextBox_PointerPressed), true);
            AddTextBox.AddHandler(PointerReleasedEvent, new PointerEventHandler(TextManipulation.AddTextBox_PointerReleased), true);
            AddTextBox.AddHandler(PointerMovedEvent, new PointerEventHandler(TextManipulation.AddTextBox_PointerMoved), true);

            textCanvas.Children.Add(AddTextBox);
            Canvas.SetLeft(AddTextBox, 30);
            Canvas.SetTop(AddTextBox, 380);

            TextBoxDelete = new Image
            {
                Source = new BitmapImage(new Uri("ms-appx:///Resources/Elements/close.png")),
                Width = 50,
                Height = 50
            };

            TransformGroup TextBoxDelete_Transform = new TransformGroup();
            TextBoxDelete_Transform.Children.Add(TextManipulation._transform);

            TextBoxDelete.RenderTransform = TextBoxDelete_Transform;

            textCanvas.Children.Add(TextBoxDelete);
            Canvas.SetLeft(TextBoxDelete, 0);
            Canvas.SetTop(TextBoxDelete, 350);


        }

    }

1010 * XAML *

        <Canvas Name="textCanvas" Width="{x:Bind DrawW}" Height="{x:Bind DrawH}"  AllowDrop="True" IsHitTestVisible="False" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0">
            <Canvas.RenderTransform>
                <TranslateTransform X="{x:Bind DrawX}" Y="{x:Bind DrawY}"/>
            </Canvas.RenderTransform>
        </Canvas>


       <PivotItem>
            <PivotItem.Header>
                <Button x:Name="TextMenu" Tapped="Textwriting_Tapped" Width="180" Height="180" Padding="0,0,0,0">
                    <Border BorderThickness="1,1,1,3" BorderBrush="#333333">
                        <Image Source="ms-appx:///Resources/textwriting.png" Stretch="UniformToFill"/>
                    </Border>
                </Button>
            </PivotItem.Header>
            <Grid Height="520">
            </Grid>
        </PivotItem>

1 Ответ

0 голосов
/ 04 сентября 2018

Привет, хотя я не могу получить ваш точный UI / UX, вот то, что я смог придумать, простая реализация, но в основном, получил ту же идею, не уверен, есть ли правильный способ сделать это, используя инструментарий или встроенные элементы управления, в любом случае, так что здесь.

Цель состоит в том, чтобы добавлять текстовые поля динамически и с кнопкой удаления рядом с ними, а затем при нажатии текстового поля будет видна кнопка удаления и, если она потеряла фокус, например, другие элементы управления получили фокус, кнопка удаления не будет видна.

enter image description here

Для этого я создал простой и грязный помощник пользовательского интерфейса, я использовал часть вашего кода для настройки свойств элементов управления.

UIHelper.cs

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

namespace App1
{
    public static class UIHelper
    {
        public static void CreateRemovableTextBoxToCanvas(Canvas canvas, string label = null)
        {
            canvas.IsHitTestVisible = true;

            InputScope scope = new InputScope();

            InputScopeName scopeName = new InputScopeName
            {
                NameValue = InputScopeNameValue.ChatWithoutEmoji
            };

            scope.Names.Add(scopeName);

            int controlIndex = canvas.Children.Count - 1;

            if (label == null)
            {
                label = "Field " + canvas.Children.Count;
            }

            TextBlock newTextBlock = new TextBlock
            {
                Text = label,
                VerticalAlignment = VerticalAlignment.Center,
                TextAlignment = TextAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Margin = new Thickness(0, 0, 10, 0)
            };

            TextBox newTextBox = new TextBox
            {
                Name = "TextBox" + controlIndex,
                Foreground = new SolidColorBrush(Colors.Black),
                Background = new SolidColorBrush(Colors.Transparent),
                BorderBrush = new SolidColorBrush(Colors.DarkGray),
                CanDrag = true,
                IsTapEnabled = true,
                PlaceholderText = "Type Text Here...",
                FontSize = 14f,
                AcceptsReturn = true,

                // Win Onscreen Keyboard Settings
                AllowFocusOnInteraction = true,
                PreventKeyboardDisplayOnProgrammaticFocus = false,
                InputScope = scope,

                ManipulationMode = ManipulationModes.All,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                Width = 130
            };

            Button deleteTextBoxButton = new Button
            {
                Name = "DeleteTextBoxButton" + controlIndex,
                Content = new StackPanel
                {
                    Children =
                    {
                        new SymbolIcon
                        {
                            Symbol = Symbol.Delete
                        },
                    }
                },
                Visibility = Visibility.Collapsed
            };

            StackPanel newTextStackPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Children = { newTextBlock, newTextBox, deleteTextBoxButton }
            };

            newTextBox.LostFocus += (s, args) => deleteTextBoxButton.Visibility = Visibility.Collapsed;
            newTextBox.GotFocus += (s, args) => deleteTextBoxButton.Visibility = Visibility.Visible;

            int topOffset = 40 * canvas.Children.Count;

            if (canvas.Children.Count > 0)
            {
                Canvas.SetLeft(newTextStackPanel, 0);
                Canvas.SetTop(newTextStackPanel, topOffset);
            }

            canvas.Children.Add(newTextStackPanel);
        }
    }
}

Вот мой xaml:

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button Grid.Row="0"
            x:Name="TextMenu"
            Tapped="Textwriting_Tapped"
            Content="Add TextBox" />
        <Canvas Grid.Row="1"
            x:Name="TextCanvas"
            Width="800"
            Height="350"
            AllowDrop="True"
            IsHitTestVisible="False"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Margin="0,15,0,0" />
    </Grid>

</Page>

А вот мой код:

using Windows.UI.Xaml.Input;

namespace App1
{
    public sealed partial class MainPage
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        public void Textwriting_Tapped(object sender, TappedRoutedEventArgs e)
        {
           UIHelper.CreateRemovableTextBoxToCanvas(TextCanvas);
        }
    }
}

Надеюсь, это поможет!

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