#c# #xamarin.forms
#c# #xamarin.forms
Вопрос:
Я создаю пользовательский элемент управления записью. У меня есть собственное представление с логикой элемента управления, главной страницей и ViewModel, где я редактирую визуальную часть элемента управления.
Я хочу определить, когда я фокусируюсь на записи, и когда я фокусирую запись, сделайте что-нибудь. Я пробовал это, но это не сработало.
Frame.xaml (пользовательский элемент управления):
<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
x:Class="CustomControl.Frame"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CustomControl"
x:Name="CustomView">
<ContentView.Content>
<StackLayout>
<!-- This is what I want to change -->
<StackLayout Orientation="Horizontal">
<Frame
Margin="0,0,0,2"
Padding="0,0,0,0"
BackgroundColor="{Binding Source={x:Reference CustomView}, Path=FrameColor}"
BorderColor="{Binding Source={x:Reference CustomView}, Path=BorderColor}"
CornerRadius="{Binding Source={x:Reference CustomView}, Path=CornerRadius}"
HasShadow="False"
HorizontalOptions="FillAndExpand">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ImageButton
Grid.Column="0"
Margin="10,0,0,0"
BackgroundColor="Transparent"
Clicked="Open"
HeightRequest="25"
HorizontalOptions="Start"
Source="{Binding Source={x:Reference CustomView}, Path=LeftSideIcon}" />
<Entry
x:Name="EntryControl"
Grid.Column="1"
Margin="0,0,30,0"
HeightRequest="25"
HorizontalOptions="FillAndExpand"
Keyboard="Chat"
Placeholder="{Binding Source={x:Reference CustomView}, Path=Placeholder}"
Text="{Binding EntryText}"
TextColor="{Binding Source={x:Reference CustomView}, Path=EntryTextColor}" />
<ImageButton
Grid.Column="1"
Margin="5"
BackgroundColor="Transparent"
Command="{Binding Source={x:Reference CustomView}, Path=DeleteMsgCommand}"
HeightRequest="25"
HorizontalOptions="End"
Source="{Binding Source={x:Reference CustomView}, Path=DeleteMessageIcon}" />
</Grid>
</Frame>
<ImageButton
Margin="0,0,5,2"
Padding="15,0,10,0"
BackgroundColor="{Binding Source={x:Reference CustomView}, Path=SendBtnColor}"
Command="{Binding Source={x:Reference CustomView}, Path=SendMsgCommand}"
CornerRadius="30"
HeightRequest="45"
HorizontalOptions="End"
Source="{Binding Source={x:Reference CustomView}, Path=RightSideIcon}"
WidthRequest="45" />
</StackLayout>
<!-- ================================ -->
<Frame
x:Name="frameemojis"
Margin="0,-8,0,0"
IsVisible="false">
<CollectionView
Margin="-10,-15,-10,-10"
HeightRequest="270"
ItemsSource="{Binding Source={x:Reference CustomView}, Path=EmojiItemSource}"
VerticalScrollBarVisibility="Never">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Horizontal" Span="5" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<ImageButton
Padding="5"
BackgroundColor="Transparent"
Command="{Binding Source={x:Reference CustomView}, Path=EmojiTappedCommand}"
CommandParameter="{Binding EmojiMethodCommand}"
HeightRequest="44"
Source="{Binding EmojiSource}"
WidthRequest="44" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</Frame>
<!-- ============== -->
</StackLayout>
</ContentView.Content>
</ContentView>
Frame.xaml.cs (пользовательский элемент управления):
public partial class Frame : ContentView
{
//===============Frame Color=====================
public static readonly BindableProperty FrameColorProperty =
BindableProperty.Create("FrameColor", typeof(Color), typeof(Frame));
public Color FrameColor
{
get { return (Color)GetValue(FrameColorProperty); }
set { SetValue(FrameColorProperty, value); }
}
//===============SendBtn Color=====================
public static readonly BindableProperty SendBtnColorProperty =
BindableProperty.Create("SendBtnColor", typeof(Color), typeof(Frame));
public Color SendBtnColor
{
get { return (Color)GetValue(SendBtnColorProperty); }
set { SetValue(SendBtnColorProperty, value); }
}
//===============Border Color=====================
public static readonly BindableProperty BorderColorProperty =
BindableProperty.Create("BorderColor", typeof(Color), typeof(Frame));
public Color BorderColor
{
get { return (Color)GetValue(BorderColorProperty); }
set { SetValue(BorderColorProperty, value); }
}
//===============Corner radius=====================
public static readonly BindableProperty CornerRadiusProperty =
BindableProperty.Create("CornerRadius", typeof(int), typeof(Frame));
public int CornerRadius
{
get { return (int)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
//===============Left side Icon=====================
public static readonly BindableProperty LeftSideIconProperty =
BindableProperty.Create("LeftSideIcon", typeof(ImageSource), typeof(Frame));
public ImageSource LeftSideIcon
{
get { return (ImageSource)GetValue(LeftSideIconProperty); }
set { SetValue(LeftSideIconProperty, value); }
}
//===============Placeholder=====================
public static readonly BindableProperty PlaceholderProperty =
BindableProperty.Create("Placeholder", typeof(string), typeof(Frame));
public string Placeholder
{
get { return (string)GetValue(PlaceholderProperty); }
set { SetValue(PlaceholderProperty, value); }
}
//===============Entry text Color=====================
public static readonly BindableProperty EntryTextColorProperty =
BindableProperty.Create("EntryTextColor", typeof(Color), typeof(Frame));
public Color EntryTextColor
{
get { return (Color)GetValue(EntryTextColorProperty); }
set { SetValue(EntryTextColorProperty, value); }
}
//===============Delete message command=====================
public static readonly BindableProperty DeleteMsgCommandProperty =
BindableProperty.Create("DeleteMsgCommand", typeof(ICommand), typeof(Frame));
public ICommand DeleteMsgCommand
{
get { return (ICommand)GetValue(DeleteMsgCommandProperty); }
set { SetValue(DeleteMsgCommandProperty, value); }
}
//===============Delete Message Icon=====================
public static readonly BindableProperty DeleteMessageIconProperty =
BindableProperty.Create("DeleteMessageIcon", typeof(ImageSource), typeof(Frame));
public ImageSource DeleteMessageIcon
{
get { return (ImageSource)GetValue(DeleteMessageIconProperty); }
set { SetValue(DeleteMessageIconProperty, value); }
}
//===============Send message command=====================
public static readonly BindableProperty SendMsgCommandProperty =
BindableProperty.Create("SendMsgCommand", typeof(ICommand), typeof(Frame));
public ICommand SendMsgCommand
{
get { return (ICommand)GetValue(SendMsgCommandProperty); }
set { SetValue(SendMsgCommandProperty, value); }
}
//===============Right side icon=====================
public static readonly BindableProperty RightSideIconProperty =
BindableProperty.Create("RightSideIcon", typeof(ImageSource), typeof(Frame));
public ImageSource RightSideIcon
{
get { return (ImageSource)GetValue(RightSideIconProperty); }
set { SetValue(RightSideIconProperty, value); }
}
//===============Item Source==========================
public static readonly BindableProperty EmojiItemSourceProperty =
BindableProperty.Create("EmojiItemSource", typeof(IList), typeof(Frame));
public IList EmojiItemSource
{
get { return (IList)GetValue(EmojiItemSourceProperty); }
set { SetValue(EmojiItemSourceProperty, value); }
}
//===============EmojiTap command=====================
public static readonly BindableProperty EmojiTappedCommandProperty =
BindableProperty.Create("EmojiTappedCommand", typeof(ICommand), typeof(Frame));
public ICommand EmojiTappedCommand
{
get { return (ICommand)GetValue(EmojiTappedCommandProperty); }
set { SetValue(EmojiTappedCommandProperty, value); }
}
public ICommand FocusedCommand { get; set; }
bool state = true;
void Open(object o, System.EventArgs e)
{
if (state)
{
state = false;
frameemojis.IsVisible = true;
}
else
{
state = true;
frameemojis.IsVisible = false;
}
}
public Frame()
{
EntryControl.Focused = (s, a) => {
if (!state)
{
state = true;
frameemojis.IsVisible = false;
}
};
InitializeComponent();
}
}
MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="App24.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:fav="clr-namespace:CustomControl;assembly=CustomControl">
<AbsoluteLayout>
<ScrollView AbsoluteLayout.LayoutBounds="0,0,1,1" AbsoluteLayout.LayoutFlags="All">
<StackLayout>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#686A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
<Frame
BackgroundColor="#806A2234"
HasShadow="True"
HeightRequest="100"
WidthRequest="100">
<Label Text="{Binding RecievedMessage}" />
</Frame>
</StackLayout>
</ScrollView>
<StackLayout
AbsoluteLayout.LayoutBounds="0,1,1,1"
AbsoluteLayout.LayoutFlags="All"
VerticalOptions="EndAndExpand">
<fav:Frame
x:Name="entrycontrol"
BorderColor="{Binding EntryBorderColor}"
CornerRadius="{Binding EntryRadius}"
DeleteMessageIcon="crossblack.png"
DeleteMsgCommand="{Binding DeleteMsgCommand}"
EmojiItemSource="{Binding EmojiList}"
EmojiTappedCommand="{Binding EmojiTappedCommand}"
EntryTextColor="{Binding TextColor}"
FrameColor="{Binding EntryBGColor}"
LeftSideIcon="icon.png"
Placeholder="Escribame"
RightSideIcon="send.png"
SendBtnColor="{Binding SendBtnColor}"
SendMsgCommand="{Binding SendMsgCommand}" />
</StackLayout>
</AbsoluteLayout>
</ContentPage>
MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
public MainPage()
{
BindingContext = new ViewModel();
InitializeComponent();
}
}
Комментарии:
1. вам нужно использовать сфокусированное событие записи
2. Я тоже пробовал и не работал. Как я должен это реализовать? Может быть, я сделал это неправильно
3. Я тестирую с помощью приведенных ниже кодов, это может вызвать событие Fouces.
Ответ №1:
используйте Focused
событие
InitializeComponent();
EntryControl.Focused = (s,a) => {
if (!state) {
state = true;
frameemojis.IsVisible = false;
}
};
Комментарии:
1. Это не сработало, я отредактировал свой пост с помощью своего кода, пытаясь это сделать. Я не знаю, почему не работает
2.во-первых, не называйте пользовательский элемент управления тем же, что и стандартный элемент пользовательского интерфейса. Это невероятно запутанно. Во-вторых, вам нужно выполнить вызов,
InitializeComponent
прежде чем вы сможете ссылаться на элемент XAML по его имени.3. Я отредактировал свой код и вызвал InitializeComponent раньше и до сих пор не работает. Я не знаю, что происходит
4. Что вы пробовали? Вы использовали отладчик, чтобы проверить, запускается ли сфокусированное событие?
5. Я попробовал строки, которые вы опубликовали. Кроме того, чтобы проверить, запускается ли событие, я пишу Debugger. Break(); когда сфокусирован, и ничего не произошло