Привязка свойства IsVisible к моей VIewModel - PullRequest
0 голосов
/ 22 марта 2020

У меня есть какая-то запись, и в фокусе этой записи я хочу показать свою кнопку отмены.

Вот xaml:

 <RelativeLayout>
                <controls:StandardEntry
                        x:Name="mainEntry"
                        BackgroundColor="White"
                        BorderColor="Gray"
                        BorderThickness="0"
                        CornerRadius="15"
                        Placeholder="Search..."
                        TextColor="LightGray"
                        HeightRequest="10"
                        Padding="35,0"
                        FontSize="Default"
                        RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height,Factor=0,Constant=40}"
                        RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,Property=Width,Factor=0.7,Constant=0}">
                    <Entry.Behaviors>
                        <behavior:EventToCommandBehavior EventName="Focused" Command="{Binding SearchBarFocusedCommand}"/>
                        <behavior:EventToCommandBehavior EventName="Unfocused" Command="{Binding SearchBarUnfocusedCommand}"/>
                    </Entry.Behaviors>
                </controls:StandardEntry>
                <Image 
                        Source="Invest_Search_Icon.png" 
                        VerticalOptions="Center"
                        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView,ElementName=mainEntry, Property=X,Factor=1,Constant=10}"
                        RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=mainEntry, Property=Y,Factor=1,Constant=10}"/>
                <Image 
                        Source="Invest_Search_Icon.png"
                        VerticalOptions="Center"
                        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView,ElementName=mainEntry, Property=Width,Factor=1,Constant=-25}"
                        RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=mainEntry, Property=Y,Factor=1,Constant=10}"/>
                <Button 
                        Text="Cancel" 
                        TextColor="Gray"
                        IsVisible="{Binding CancelButtonIsVisible}"
                        BackgroundColor="White"
                        VerticalOptions="Start" 
                        CornerRadius="10" 
                        HeightRequest="40" 
                        Margin="0,0,50,0"
                        RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView,ElementName=mainEntry, Property=Width,Factor=1,Constant=20}"
                        RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=mainEntry, Property=Y,Factor=1,Constant=0}"/>
            </RelativeLayout>

Как вы видите Imusing EventToCommand Behavior, который это нормально работает (это входит в мои командные методы). В моей виртуальной машине:

    public class InvestViewModel : BaseViewModel, INotifyPropertyChanged
    {
        public InvestViewModel()
        {
            SetDefaultContent();
            SearchBarFocusedCommand = new Command(() => OnSearchBarFocused());
        }

        private void OnSearchBarUnfocused()
        {
            CancelButtonIsVisible = false;
        }

        private void OnSearchBarFocused()
        {
           CancelButtonIsVisible = false;
        }

        private void SetDefaultContent()
        {
            CancelButtonIsVisible = true;
        }



        private bool cancelButtonIsVisible;
        public bool CancelButtonIsVisible
        {
            get => cancelButtonIsVisible;
            set
            {
                cancelButtonIsVisible = value;
                RaisePropertyChanged(() => CancelButtonIsVisible);
            }
        }

        public ICommand CancelClickCommand { get; set; }
        public ICommand SearchBarFocusedCommand { get; set; }
    }

Итак, поток:

  1. При загрузке страницы, сначала SetDefaultContent () => CancelButtonIsVisible = true;
  2. При входе сосредоточены, скрыть кнопка отмены OnSearchBarFocused () => CancelButtonIsVisible = false;

Очевидно, SetDefaultContent работает .

Не работает мой метод фокусировки, когда я сфокусировался, ничего не происходит, все еще видна кнопка отмены.

enter image description here

Есть предложения?

1 Ответ

0 голосов
/ 22 марта 2020

Option-1

Более простой вариант - связать свойство IsVisible на кнопке «Отмена» с IsFocused свойством элемента управления entry (mainEntry) с использованием именованной ссылки.

<Button Text="Cancel" 
     IsVisible="{Binding IsFocused, Source={x:Reference mainEntry}, 
                     Converter={StaticResource NegateBooleanConverter}}" />

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

public class NegateBooleanConverter : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(bool)value;
    }
    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(bool)value;
    }
}

Option-2

Другой вариант - связать IsFocused со свойством view-model.

Создание свойства с помощью setter в viewmodel

public bool IsEntryFocused
{
   set
   {
      CancelButtonIsVisible = !value;
   }
}

и настройка привязки в представлении

<controls:StandardEntry
     x:Name="mainEntry"
     ...
     IsFocused="{Binding IsEntryFocused}"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...