问:
disable text box selection brush
I have several text boxes in my project and when the program is running and select one of them, a white rectangle appears on back of text box and caret starts blinking, is there a way to get rid of this white box and caret  ? So when tapping on text box just clear the text inside ?</p>

答:
is there a way to get rid of this white box and caret

The white box is actually the BorderElement of the detault TextBox styles and templates. You can change the default style of the Textbox to what you want. For example, commented out the time lines inside the style which is changing the BorderElement background color and then the white background color will not appear.

```<code><!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
     <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
 </ObjectAnimationUsingKeyFrames>-->
</code>```

For caret, you may set the TextBox as ReadOnly once the Textbox get focused, or let the other controls to get focus to let the TextBox lose focus so that the cursor may not appear.

So when tapping on text box just clear the text inside

For this, you can clear the text when the Textbox got focus.

Following is a simple demo may implement what you want you may reference:

```<code><Page.Resources>
   <Style x:Key="TextBoxStyle1" TargetType="TextBox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Grid>
                        <Grid.Resources>
                            <Style x:Name="DeleteButtonStyle" TargetType="Button">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="Button">
                                            <Grid
                                                x:Name="ButtonLayoutGrid"
                                                Background="{ThemeResource TextControlButtonBackground}"
                                                BorderBrush="{ThemeResource TextControlButtonBorderBrush}"
                                                BorderThickness="{TemplateBinding BorderThickness}">
                                                <TextBlock
                                                    x:Name="GlyphElement"
                                                    HorizontalAlignment="Center"
                                                    VerticalAlignment="Center"
                                                    Foreground="{ThemeResource TextControlButtonForeground}"
                                                    FontFamily="{ThemeResource SymbolThemeFontFamily}"
                                                    FontSize="12"
                                                    FontStyle="Normal"
                                                    AutomationProperties.AccessibilityView="Raw"
                                                    Text="" />
                                                <VisualStateManager.VisualStateGroups>
                                                    <VisualStateGroup x:Name="CommonStates">
                                                        <VisualState x:Name="Normal" />
                                                        <VisualState x:Name="PointerOver">
                                                            <Storyboard>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPointerOver}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="BorderBrush">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPointerOver}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPointerOver}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                            </Storyboard>
                                                        </VisualState>
                                                        <VisualState x:Name="Pressed">
                                                            <Storyboard>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPressed}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="BorderBrush">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPressed}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPressed}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                            </Storyboard>
                                                        </VisualState>
                                                        <VisualState x:Name="Disabled">
                                                            <Storyboard>
                                                                <DoubleAnimation
                                                                    Duration="0"
                                                                    Storyboard.TargetName="ButtonLayoutGrid"
                                                                    Storyboard.TargetProperty="Opacity"
                                                                    To="0" />
                                                            </Storyboard>
                                                        </VisualState>
                                                    </VisualStateGroup>
                                                </VisualStateManager.VisualStateGroups>
                                            </Grid>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </Grid.Resources>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Border
                            x:Name="BorderElement"
                            Grid.Row="1"
                            Grid.RowSpan="1"
                            Grid.ColumnSpan="2"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}" />
                        <ContentPresenter
                            x:Name="HeaderContentPresenter"
                            Grid.Row="0"
                            Grid.ColumnSpan="2"
                            Margin="0,0,0,8"
                            Foreground="{ThemeResource TextControlHeaderForeground}"
                            FontWeight="Normal"
                            x:DeferLoadStrategy="Lazy"
                            Content="{TemplateBinding Header}"
                            ContentTemplate="{TemplateBinding HeaderTemplate}"
                            Visibility="Collapsed" />
                        <ScrollViewer
                            x:Name="ContentElement"
                            Grid.Row="1"
                            Margin="{TemplateBinding BorderThickness}"
                            Padding="{TemplateBinding Padding}"
                            AutomationProperties.AccessibilityView="Raw"
                            HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
                            HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
                            IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
                            IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
                            IsTabStop="False"
                            IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
                            VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
                            VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
                            ZoomMode="Disabled" />
                        <ContentControl
                            x:Name="PlaceholderTextContentPresenter"
                            Grid.Row="1"
                            Grid.ColumnSpan="2"
                            Margin="{TemplateBinding BorderThickness}"
                            Padding="{TemplateBinding Padding}"
                            Foreground="{ThemeResource TextControlPlaceholderForeground}"
                            Content="{TemplateBinding PlaceholderText}"
                            IsHitTestVisible="False"
                            IsTabStop="False" />
                        <Button
                            x:Name="DeleteButton"
                            Grid.Row="1"
                            Grid.Column="1"
                            MinWidth="34"
                            Margin="{ThemeResource HelperButtonThemePadding}"
                            VerticalAlignment="Stretch"
                            Style="{StaticResource DeleteButtonStyle}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            FontSize="{TemplateBinding FontSize}"
                            AutomationProperties.AccessibilityView="Raw"
                            IsTabStop="False"
                            Visibility="Collapsed" />
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
                                        </ObjectAnimationUsingKeyFrames>-->
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="PointerOver">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>
                                        </ObjectAnimationUsingKeyFrames>-->
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundPointerOver}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Focused">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}"/>
                                        </ObjectAnimationUsingKeyFrames>-->
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="RequestedTheme">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="Light" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="ButtonStates">
                                <VisualState x:Name="ButtonVisible">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DeleteButton" Storyboard.TargetProperty="Visibility">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Visible</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="ButtonCollapsed" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" x:Name="Gridroot" Padding="50">
   <Button x:Name="btnforfocus"></Button>
   <TextBox
       x:Name="txttest"
       Width="300"
       Height="50"
       Style="{StaticResource TextBoxStyle1}"
       Background="Azure"
       BorderThickness="0"
       FocusVisualPrimaryBrush="White"
       Text="aaaaa"
       GotFocus="txttest_GotFocus"
       />
</StackPanel>
</code>```

Code behind

```<code>private void txttest_GotFocus(object sender, RoutedEventArgs e)
{
    txttest.Text = "";
    try
    {
        btnforfocus.Focus(FocusState.Pointer);
        //txttest.IsReadOnly = true;
    }
    catch(Exception ex)
    {
    }
}
</code>```

You can change the style for a  Textbox by setting its properties  or update the control's default style and template. More details please reference Textbox.

Title: disable text box selection brush

Body:
is there a way to get rid of this white box and caret

The white box is actually the BorderElement of the detault TextBox styles and templates. You can change the default style of the Textbox to what you want. For example, commented out the time lines inside the style which is changing the BorderElement background color and then the white background color will not appear.

<!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
     <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
 </ObjectAnimationUsingKeyFrames>-->

For caret, you may set the TextBox as ReadOnly once the Textbox get focused, or let the other controls to get focus to let the TextBox lose focus so that the cursor may not appear.

So when tapping on text box just clear the text inside

For this, you can clear the text when the Textbox got focus.

Following is a simple demo may implement what you want you may reference:

<Page.Resources>
   <Style x:Key="TextBoxStyle1" TargetType="TextBox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Grid>
                        <Grid.Resources>
                            <Style x:Name="DeleteButtonStyle" TargetType="Button">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="Button">
                                            <Grid
                                                x:Name="ButtonLayoutGrid"
                                                Background="{ThemeResource TextControlButtonBackground}"
                                                BorderBrush="{ThemeResource TextControlButtonBorderBrush}"
                                                BorderThickness="{TemplateBinding BorderThickness}">
                                                <TextBlock
                                                    x:Name="GlyphElement"
                                                    HorizontalAlignment="Center"
                                                    VerticalAlignment="Center"
                                                    Foreground="{ThemeResource TextControlButtonForeground}"
                                                    FontFamily="{ThemeResource SymbolThemeFontFamily}"
                                                    FontSize="12"
                                                    FontStyle="Normal"
                                                    AutomationProperties.AccessibilityView="Raw"
                                                    Text="&#xE10A;" />
                                                <VisualStateManager.VisualStateGroups>
                                                    <VisualStateGroup x:Name="CommonStates">
                                                        <VisualState x:Name="Normal" />
                                                        <VisualState x:Name="PointerOver">
                                                            <Storyboard>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPointerOver}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="BorderBrush">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPointerOver}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPointerOver}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                            </Storyboard>
                                                        </VisualState>
                                                        <VisualState x:Name="Pressed">
                                                            <Storyboard>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBackgroundPressed}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="BorderBrush">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonBorderBrushPressed}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                    <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlButtonForegroundPressed}" />
                                                                </ObjectAnimationUsingKeyFrames>
                                                            </Storyboard>
                                                        </VisualState>
                                                        <VisualState x:Name="Disabled">
                                                            <Storyboard>
                                                                <DoubleAnimation
                                                                    Duration="0"
                                                                    Storyboard.TargetName="ButtonLayoutGrid"
                                                                    Storyboard.TargetProperty="Opacity"
                                                                    To="0" />
                                                            </Storyboard>
                                                        </VisualState>
                                                    </VisualStateGroup>
                                                </VisualStateManager.VisualStateGroups>
                                            </Grid>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </Grid.Resources>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <Border
                            x:Name="BorderElement"
                            Grid.Row="1"
                            Grid.RowSpan="1"
                            Grid.ColumnSpan="2"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}" />
                        <ContentPresenter
                            x:Name="HeaderContentPresenter"
                            Grid.Row="0"
                            Grid.ColumnSpan="2"
                            Margin="0,0,0,8"
                            Foreground="{ThemeResource TextControlHeaderForeground}"
                            FontWeight="Normal"
                            x:DeferLoadStrategy="Lazy"
                            Content="{TemplateBinding Header}"
                            ContentTemplate="{TemplateBinding HeaderTemplate}"
                            Visibility="Collapsed" />
                        <ScrollViewer
                            x:Name="ContentElement"
                            Grid.Row="1"
                            Margin="{TemplateBinding BorderThickness}"
                            Padding="{TemplateBinding Padding}"
                            AutomationProperties.AccessibilityView="Raw"
                            HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
                            HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
                            IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
                            IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
                            IsTabStop="False"
                            IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
                            VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
                            VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
                            ZoomMode="Disabled" />
                        <ContentControl
                            x:Name="PlaceholderTextContentPresenter"
                            Grid.Row="1"
                            Grid.ColumnSpan="2"
                            Margin="{TemplateBinding BorderThickness}"
                            Padding="{TemplateBinding Padding}"
                            Foreground="{ThemeResource TextControlPlaceholderForeground}"
                            Content="{TemplateBinding PlaceholderText}"
                            IsHitTestVisible="False"
                            IsTabStop="False" />
                        <Button
                            x:Name="DeleteButton"
                            Grid.Row="1"
                            Grid.Column="1"
                            MinWidth="34"
                            Margin="{ThemeResource HelperButtonThemePadding}"
                            VerticalAlignment="Stretch"
                            Style="{StaticResource DeleteButtonStyle}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            FontSize="{TemplateBinding FontSize}"
                            AutomationProperties.AccessibilityView="Raw"
                            IsTabStop="False"
                            Visibility="Collapsed" />
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>
                                        </ObjectAnimationUsingKeyFrames>-->
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundDisabled}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="PointerOver">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>
                                        </ObjectAnimationUsingKeyFrames>-->
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundPointerOver}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Focused">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <!--<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="BorderElement">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}"/>
                                        </ObjectAnimationUsingKeyFrames>-->
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="RequestedTheme">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="Light" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="ButtonStates">
                                <VisualState x:Name="ButtonVisible">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DeleteButton" Storyboard.TargetProperty="Visibility">
                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                <DiscreteObjectKeyFrame.Value>
                                                    <Visibility>Visible</Visibility>
                                                </DiscreteObjectKeyFrame.Value>
                                            </DiscreteObjectKeyFrame>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="ButtonCollapsed" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Page.Resources>

<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" x:Name="Gridroot" Padding="50">
   <Button x:Name="btnforfocus"></Button>
   <TextBox
       x:Name="txttest"
       Width="300"
       Height="50"
       Style="{StaticResource TextBoxStyle1}"
       Background="Azure"
       BorderThickness="0"
       FocusVisualPrimaryBrush="White"
       Text="aaaaa"
       GotFocus="txttest_GotFocus"
       />
</StackPanel>

Code behind

private void txttest_GotFocus(object sender, RoutedEventArgs e)
{
    txttest.Text = "";
    try
    {
        btnforfocus.Focus(FocusState.Pointer);
        //txttest.IsReadOnly = true;
    }
    catch(Exception ex)
    {
    }
}

You can change the style for a  Textbox by setting its properties  or update the control's default style and template. More details please reference Textbox.


来源: stackexchange

问:
Ajax data not binding properly in the dropdownlist
I have a gridview in which there are multiple rows with Edit options in each row. So what exactly the scenario is,
whenever I click on EDIT button it will redirect me to next tab with the SAP ID of that row filled in the dropdownlist.

But currently what happening is, when I click the edit button for the first time, it shows only one value in the list,

but when I
  click second time, the list shows me two values. I dont want that, I want only the data value for which I have clicked the edit button.

Below is my GridView and ajax code for binding values

GRIDVIEW

```<code><asp:GridView ID="grdSapDetails" runat="server" PageSize="10" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="SAP_ID" HeaderText="Sap Id" />
                    <asp:BoundField DataField="SITE_NAME" HeaderText="Site Name" />
                    <asp:BoundField DataField="SITE_ADDRESS" HeaderText="Site Address" />
                    <asp:TemplateField HeaderText="Edit">
                        <ItemTemplate>
                            <input type="button" onclick='return HighlightTabFunction(this)' value="Edit" id="btnEdit" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
</code>```

AJAX

```<code>function HighlightTabFunction(a) {
        var row = a.parentNode.parentNode;
        var rowIndex = row.rowIndex - 1;
        var SAPID = row.cells[0].innerHTML;
        $.ajax({
            url: "UBRDashboard.aspx/GETSTATEFROM_SAP",
            dataType: "json",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ SAPID: SAPID }),
            async: true,
            processData: false,
            cache: false,
            success: function (r) {
                $('a[href="#tabs-2"]').click();
                var ddlSapID = $("[id*=ddlSapID]");
                ddlSapID.append($("<option></option>").val(r.d).html(row.cells[0].innerHTML));
                $("#hdnState").val(r.d);
            },
            error: function (xhr) {
                alert('Error while selecting list..!!');
            }
        })
</code>```

答:
You probably have to remove the dropdown list item before you add new. You can call remove() on children of dropdown (select)

```<code>success: function (r) {
            $('a[href="#tabs-2"]').click();
            var ddlSapID = $("[id*=ddlSapID]");
            ddlSapID.children().remove(); //this will remove option before appending new
            ddlSapID.append($("<option></option>").val(r.d).html(row.cells[0].innerHTML));
            $("#hdnState").val(r.d);
        },
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a gridview in which there are multiple rows with Edit options in each row. So what exactly the scenario is,
whenever I click on EDIT button it will redirect me to next tab with the SAP ID of that row filled in the dropdownlist.

But currently what happening is, when I click the edit button for the first time, it shows only one value in the list,

but when I
  click second time, the list shows me two values. I dont want that, I want only the data value for which I have clicked the edit button.

Below is my GridView and ajax code for binding values

GRIDVIEW

<asp:GridView ID="grdSapDetails" runat="server" PageSize="10" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="SAP_ID" HeaderText="Sap Id" />
                    <asp:BoundField DataField="SITE_NAME" HeaderText="Site Name" />
                    <asp:BoundField DataField="SITE_ADDRESS" HeaderText="Site Address" />
                    <asp:TemplateField HeaderText="Edit">
                        <ItemTemplate>
                            <input type="button" onclick='return HighlightTabFunction(this)' value="Edit" id="btnEdit" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

AJAX

function HighlightTabFunction(a) {
        var row = a.parentNode.parentNode;
        var rowIndex = row.rowIndex - 1;
        var SAPID = row.cells[0].innerHTML;
        $.ajax({
            url: "UBRDashboard.aspx/GETSTATEFROM_SAP",
            dataType: "json",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ SAPID: SAPID }),
            async: true,
            processData: false,
            cache: false,
            success: function (r) {
                $('a[href="#tabs-2"]').click();
                var ddlSapID = $("[id*=ddlSapID]");
                ddlSapID.append($("<option></option>").val(r.d).html(row.cells[0].innerHTML));
                $("#hdnState").val(r.d);
            },
            error: function (xhr) {
                alert('Error while selecting list..!!');
            }
        })

Body:
You probably have to remove the dropdown list item before you add new. You can call remove() on children of dropdown (select)

success: function (r) {
            $('a[href="#tabs-2"]').click();
            var ddlSapID = $("[id*=ddlSapID]");
            ddlSapID.children().remove(); //this will remove option before appending new
            ddlSapID.append($("<option></option>").val(r.d).html(row.cells[0].innerHTML));
            $("#hdnState").val(r.d);
        },


问:
Data is not updating in the firebase data. However, it reflects the update in the html page
This function is used to update and save the data into the firebase database. It's not working properly as I put the breaking at the save function, control doesn't enter the function. The changed data is reflected in the html but not in the firebase database.   </p>

```<code>$scope.editFormSubmit = function(){
            console.log("Updating record");

            //Get ID
            var id = $scope.id;
            console.log(id);

            //Get Record
            var rec = $scope.records.$getRecord(id);
            console.log(rec);
            //Assign Values
            rec.fname = $scope.fname;
            rec.lname = $scope.lname;
            rec.mname = $scope.mname;
            rec.email = $scope.email;
            rec.company = $scope.company;
            rec.phone = $scope.phone;
            rec.city = $scope.city;
            rec.state = $scope.state;
            rec.zipCode = $scope.zipCode;
            rec.conId = $scope.conId;
            rec.DCN = $scope.DCN;
            rec.jobTitle = $scope.jobTitle;
            rec.pAddress = $scope.pAddress;
            rec.country = $scope.country;
            rec.name = $scope.name;

            // Save Record
            console.log("After assigning values");
            console.log(rec);

            $scope.records.$save(rec).then(function(){
                console.log("Updating values");
            });

            clearFields();

            //hide the edit form
            $scope.editFormShow = false;
            $scope.msg = "Contact Update";
        }
</code>```

答:
Did you try </p>

```<code>$scope.records.$save(rec).then(function(){
                console.log("Updating values");
            }, function(error) {
                console.log(error);
});
</code>```

Body:
This function is used to update and save the data into the firebase database. It's not working properly as I put the breaking at the save function, control doesn't enter the function. The changed data is reflected in the html but not in the firebase database.

$scope.editFormSubmit = function(){
            console.log("Updating record");

            //Get ID
            var id = $scope.id;
            console.log(id);

            //Get Record
            var rec = $scope.records.$getRecord(id);
            console.log(rec);
            //Assign Values
            rec.fname = $scope.fname;
            rec.lname = $scope.lname;
            rec.mname = $scope.mname;
            rec.email = $scope.email;
            rec.company = $scope.company;
            rec.phone = $scope.phone;
            rec.city = $scope.city;
            rec.state = $scope.state;
            rec.zipCode = $scope.zipCode;
            rec.conId = $scope.conId;
            rec.DCN = $scope.DCN;
            rec.jobTitle = $scope.jobTitle;
            rec.pAddress = $scope.pAddress;
            rec.country = $scope.country;
            rec.name = $scope.name;

            // Save Record
            console.log("After assigning values");
            console.log(rec);

            $scope.records.$save(rec).then(function(){
                console.log("Updating values");
            });

            clearFields();

            //hide the edit form
            $scope.editFormShow = false;
            $scope.msg = "Contact Update";
        }

Body:
Did you try

$scope.records.$save(rec).then(function(){
                console.log("Updating values");
            }, function(error) {
                console.log(error);
});


问:
Mercurial, abort: authorization failed
I'm having problems accessing a mercurial repository. (mercurial 1.7.1)

Its set up on IIS6 windows 2003 over Https,

I can access the site through a browser using the same credentials,

I can access the site if I enable anonymous access for the virtual directory in IIS, but I need to use the Integrated Windows authentication.

I have tried setting the path in my hgrc file to:

```<code>[paths]
default = https://username:password@example.site.com/hg/hgweb.cgi/TestRepository
</code>```

then if I try to Push or Pull I get the error message:

abort: authorization failed

Any Ideas?

答: I have changed the Directory security authentication mode to basic authentication. For the time being this seem to be sufficient for our needs  </p>

ContentLicense: CC BY-SA 2.5

Title: Mercurial, abort: authorization failed

Body:
I'm having problems accessing a mercurial repository. (mercurial 1.7.1)

Its set up on IIS6 windows 2003 over Https,

I can access the site through a browser using the same credentials,

I can access the site if I enable anonymous access for the virtual directory in IIS, but I need to use the Integrated Windows authentication.

I have tried setting the path in my hgrc file to:

[paths]
default = https://username:password@example.site.com/hg/hgweb.cgi/TestRepository

then if I try to Push or Pull I get the error message:

abort: authorization failed

Any Ideas?


问:
passing a closure to addTarget in Swift
I have a method that gets movies from an api and then loads the data into the UITableView.  I want to reuse the network calls for a refresh control and at the end of the http get request, to call a completion handler that basically stops the refresh control once it's successful.  Is that possible?

```<code>func getMovies(completion: (() -> ())?) {
    SVProgressHUD.show()
    Alamofire.request("https://api.moviesite").responseJSON {
        response in
        switch response.result {
        case .success(let data):
            if let json = data as? NSDictionary {
                self.movieResults = json["results"] as! [NSDictionary]
                self.nowPlayingTableView.reloadData()
            }
        case .failure(let error):
            print(error)
            self.showNetworkError(show: true)
        }

        SVProgressHUD.dismiss()
        if completion != nil {
            completion!()
        }
    }
}
</code>```

And when I use this method in viewDidLoad, I'd like to do something like this:

```<code>let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(NowPlayingViewController.getMovies(refreshControl.endRefreshing)), for: .valueChanged)
        nowPlayingTableView.insertSubview(refreshControl, at: 0)
</code>```

but I get a compiler error about

getMovies cannot be used, did you mean to use a value type instead?

答:
The only selector that you set with UIRefreshControl is #selector(refreshing) or #selector(refreshing(_:)) means selector either with UIRefreshControl as parameter or without any parameter. If you want to end the refreshing then try like this.

```<code>let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshing(_:)), for: .valueChanged)
nowPlayingTableView.insertSubview(refreshControl, at: 0)
</code>```

Now add one action refreshing with your controller and call getMovies with it and in completion of your getMovies call the endRefreshing on UIRefreshControl

```<code>func refreshing(_ sender: UIRefreshControl) {
    self.getMovies() {
        sender.endRefreshing()
    }
}
</code>```

Title: passing a closure to addTarget in Swift

Body:
I have a method that gets movies from an api and then loads the data into the UITableView.  I want to reuse the network calls for a refresh control and at the end of the http get request, to call a completion handler that basically stops the refresh control once it's successful.  Is that possible?

func getMovies(completion: (() -> ())?) {
    SVProgressHUD.show()
    Alamofire.request("https://api.moviesite").responseJSON {
        response in
        switch response.result {
        case .success(let data):
            if let json = data as? NSDictionary {
                self.movieResults = json["results"] as! [NSDictionary]
                self.nowPlayingTableView.reloadData()
            }
        case .failure(let error):
            print(error)
            self.showNetworkError(show: true)
        }

        SVProgressHUD.dismiss()
        if completion != nil {
            completion!()
        }
    }
}

And when I use this method in viewDidLoad, I'd like to do something like this:

let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(NowPlayingViewController.getMovies(refreshControl.endRefreshing)), for: .valueChanged)
        nowPlayingTableView.insertSubview(refreshControl, at: 0)

but I get a compiler error about

getMovies cannot be used, did you mean to use a value type instead?

Body:
The only selector that you set with UIRefreshControl is #selector(refreshing) or #selector(refreshing(_:)) means selector either with UIRefreshControl as parameter or without any parameter. If you want to end the refreshing then try like this.

let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshing(_:)), for: .valueChanged)
nowPlayingTableView.insertSubview(refreshControl, at: 0)

Now add one action refreshing with your controller and call getMovies with it and in completion of your getMovies call the endRefreshing on UIRefreshControl

func refreshing(_ sender: UIRefreshControl) {
    self.getMovies() {
        sender.endRefreshing()
    }
}


问:
Programatically Select a combobox item using the SelectedValue WPF
I have a combo box which is loaded through a Datasource(Datatable). On a scenario I want the combo box to load with the desired value which I would be passing as combobox1.SelectedValue = custId (Say it's a customer details). custID is set as SelectedValuePath in XAML. When I set that, I am getting a null exception. Anything I am missing?

My XAML:

```<code><ComboBox Height="23" HorizontalAlignment="Left" Margin="332,42,0,0" Name="cmbCustomerName" VerticalAlignment="Top" Width="240" IsEditable="True" DisplayMemberPath="customername" SelectedValuePath="custid" ItemsPanel="{StaticResource cust}" SelectionChanged="cmbCustomerName_SelectionChanged" AllowDrop="True" FontWeight="Normal" Text="--Select a Customer Name--" IsSynchronizedWithCurrentItem="True" />
</code>```

UPDATE:

C# code:

```<code>public customer(int custid)
{
   InitializeComponent();
   cmbcustomer.SelectedValue= custid.ToString();
}

private void cmbCustomerName_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      cmbcustid.SelectedValue= cmbcustomer.SelectedValue;
    }
</code>```

答: I got the issue resolved by assigning the value in the combox_loaded event, as the combobox was just initialized in the constructor, but it was not loaded from the datasource.</p>

Body:
I have a combo box which is loaded through a Datasource(Datatable). On a scenario I want the combo box to load with the desired value which I would be passing as combobox1.SelectedValue = custId (Say it's a customer details). custID is set as SelectedValuePath in XAML. When I set that, I am getting a null exception. Anything I am missing?

My XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="332,42,0,0" Name="cmbCustomerName" VerticalAlignment="Top" Width="240" IsEditable="True" DisplayMemberPath="customername" SelectedValuePath="custid" ItemsPanel="{StaticResource cust}" SelectionChanged="cmbCustomerName_SelectionChanged" AllowDrop="True" FontWeight="Normal" Text="--Select a Customer Name--" IsSynchronizedWithCurrentItem="True" />

UPDATE:

C# code:

public customer(int custid)
{
   InitializeComponent();
   cmbcustomer.SelectedValue= custid.ToString();
}

private void cmbCustomerName_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      cmbcustid.SelectedValue= cmbcustomer.SelectedValue;
    }


问:
java polymorphism and inheritance problems
Firstly, I though that java's Polymorphism functions are mapped by it types of parameter instance.

Please, someone help to explain why my function haven't called to myFunction(EmployeeImpl emp) sign it instance is EmployeeImpl.

```<code>public class MainApp {
  public static void main(String[] args){
    Employee emp = new EmployeeImpl();
    emp.callMyFunction();
  }
}

abstract class Employee{
  public void callMyFunction(){
    //here is huge amount of code, which all child class has the same
    //excepted this line is called to a different function by it instant types.
    EmployeeFacade.myFunction(this);
  }
}
class EmployeeImpl extends Employee{

}
class EmployeeFacade{
  public static void myFunction(Employee emp){
    //same data to database
    System.out.println("Employee: "+ emp.getClass().getName());
  }
  public static void myFunction(EmployeeImpl emp){
    //same data to database
    System.out.println("EmployeeImpl: "+ emp.getClass().getName());
  }
}
</code>```

Result: Employee: EmployeeImpl

Edited: This is just a sample application with the same structure as my reality application, which has more than 20 children classes that contain the same function called callMyFunction, this function has more than 20 lines of code. so it's a very hard work for me to override this function with the same code code for all children class. Anyways, What will happen if I need to change my function on the future? Would I change all 20 function with the same code?

Are there anyways easier than this?

答:
My first solution (as I suggested in comments) would be to move myFunction from the EmployeeFacade to Employee, EmployeeImpl and other subclasses and thus use virtual methods directly. If this for some reasons is not an option, my next solution would be introducing virtual "proxy" function to Employee and using it to dispatch call properly:

```<code>public class MainApp {
  public static void main(String[] args){
    Employee emp = new EmployeeImpl();
    emp.callMyFunction();
  }
}

abstract class Employee
{
    public void callMyFunction()
    {
        //here is huge amount of code, which all child class has the same
        //excepted this line is called to a different function by it instant types.
        callMyFunctionImpl();
    }

    protected void callMyFunctionImpl()
    {
        EmployeeFacade.myFunction(this);
    }
}

class EmployeeImpl extends Employee
{
    @Override
    protected void callMyFunctionImpl()
    {
        EmployeeFacade.myFunction(this);
    }
}

class EmployeeFacade
{
    public static void myFunction(Employee emp)
    {
        //same data to database
        System.out.println("Employee: " + emp.getClass().getName());
    }

    public static void myFunction(EmployeeImpl emp)
    {
        //same data to database
        System.out.println("EmployeeImpl: " + emp.getClass().getName());
    }
}
</code>```

Body:
Firstly, I though that java's Polymorphism functions are mapped by it types of parameter instance.

Please, someone help to explain why my function haven't called to myFunction(EmployeeImpl emp) sign it instance is EmployeeImpl.

public class MainApp {
  public static void main(String[] args){
    Employee emp = new EmployeeImpl();
    emp.callMyFunction();
  }
}

abstract class Employee{
  public void callMyFunction(){
    //here is huge amount of code, which all child class has the same
    //excepted this line is called to a different function by it instant types.
    EmployeeFacade.myFunction(this);
  }
}
class EmployeeImpl extends Employee{

}
class EmployeeFacade{
  public static void myFunction(Employee emp){
    //same data to database
    System.out.println("Employee: "+ emp.getClass().getName());
  }
  public static void myFunction(EmployeeImpl emp){
    //same data to database
    System.out.println("EmployeeImpl: "+ emp.getClass().getName());
  }
}

Result: Employee: EmployeeImpl

Edited: This is just a sample application with the same structure as my reality application, which has more than 20 children classes that contain the same function called callMyFunction, this function has more than 20 lines of code. so it's a very hard work for me to override this function with the same code code for all children class. Anyways, What will happen if I need to change my function on the future? Would I change all 20 function with the same code?

Are there anyways easier than this?

Body:
My first solution (as I suggested in comments) would be to move myFunction from the EmployeeFacade to Employee, EmployeeImpl and other subclasses and thus use virtual methods directly. If this for some reasons is not an option, my next solution would be introducing virtual "proxy" function to Employee and using it to dispatch call properly:

public class MainApp {
  public static void main(String[] args){
    Employee emp = new EmployeeImpl();
    emp.callMyFunction();
  }
}

abstract class Employee
{
    public void callMyFunction()
    {
        //here is huge amount of code, which all child class has the same
        //excepted this line is called to a different function by it instant types.
        callMyFunctionImpl();
    }

    protected void callMyFunctionImpl()
    {
        EmployeeFacade.myFunction(this);
    }
}

class EmployeeImpl extends Employee
{
    @Override
    protected void callMyFunctionImpl()
    {
        EmployeeFacade.myFunction(this);
    }
}

class EmployeeFacade
{
    public static void myFunction(Employee emp)
    {
        //same data to database
        System.out.println("Employee: " + emp.getClass().getName());
    }

    public static void myFunction(EmployeeImpl emp)
    {
        //same data to database
        System.out.println("EmployeeImpl: " + emp.getClass().getName());
    }
}


问:
how to support more than one datetime pattern

How to support more than one datetime pattern like yyyyMMdd and yyyy-MM-dd?

答:
With SimpleDateFormat, you can set your own date patterns. For example, dd/mm/yyyy, mm/dd/yyyy, yyyy-mm-dd, and so on.

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):

```<code>Letter   Date or Time Component   Presentation       Examples
G        Era designator             Text                AD
y        Year                       Year                1996;    96
M        Month in year               Month               July; Jul; 07
w        Week in year               Number               27
W        Week in month               Number               2
D        Day in year               Number               189
d        Day in month               Number               10
F        Day of week in month       Number               2
E        Day in week               Text               Tuesday; Tue
a        Am/pm marker               Text               PM
H        Hour in day (0-23)       Number               0
k        Hour in day (1-24)       Number               24
K        Hour in am/pm (0-11)       Number               0
h        Hour in am/pm (1-12)       Number               12
m        Minute in hour           Number               30
s        Second in minute           Number               55
S        Millisecond                Number               978
z        Time zone                   General time zone   Pacific Standard Time; PST; GMT-08:00
Z        Time zone                  RFC 822 time zone   -0800

(from Java API doc)
</code>```

Source

```<code>import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainClass {
  public static void main(String[] args) {
    String pattern = "MM/dd/yyyy";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    try {
      Date date = format.parse("12/31/2006");
      System.out.println(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    // formatting
    System.out.println(format.format(new Date()));
  }
}
</code>```

Output

```<code>Sun Dec 31 00:00:00 PST 2006
01/26/2007
</code>```

Body:
With SimpleDateFormat, you can set your own date patterns. For example, dd/mm/yyyy, mm/dd/yyyy, yyyy-mm-dd, and so on.

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved):

Letter   Date or Time Component   Presentation       Examples
G        Era designator             Text                AD
y        Year                       Year                1996;    96
M        Month in year               Month               July; Jul; 07
w        Week in year               Number               27
W        Week in month               Number               2
D        Day in year               Number               189
d        Day in month               Number               10
F        Day of week in month       Number               2
E        Day in week               Text               Tuesday; Tue
a        Am/pm marker               Text               PM
H        Hour in day (0-23)       Number               0
k        Hour in day (1-24)       Number               24
K        Hour in am/pm (0-11)       Number               0
h        Hour in am/pm (1-12)       Number               12
m        Minute in hour           Number               30
s        Second in minute           Number               55
S        Millisecond                Number               978
z        Time zone                   General time zone   Pacific Standard Time; PST; GMT-08:00
Z        Time zone                  RFC 822 time zone   -0800

(from Java API doc)

Source

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainClass {
  public static void main(String[] args) {
    String pattern = "MM/dd/yyyy";
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    try {
      Date date = format.parse("12/31/2006");
      System.out.println(date);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    // formatting
    System.out.println(format.format(new Date()));
  }
}

Output

Sun Dec 31 00:00:00 PST 2006
01/26/2007


问:
Is there a vim command to select pasted text?
I find myself often repeating the following pattern of operations.

I usually go into visual mode, select some lines or block. Then I yank them using y, and paste them using p or P. The next step is to select the pasted text, to replace a variable or function name or change indentation.

I know that I can use gvto reselect the "origin" but what I would like is a similar command to select the "destination".

:help gv mentions :

After using "p" or "P" in Visual mode the text that was put will be selected.

but it is only useful when you are replacing a selection by the content of register, not when you are inserting a whole new block.

答:
You are looking for

```<code>`[v`]
</code>```

'[ and '] are marks automatically set by vim to the start and the end of the "previously changed or yanked text". v switches to visual mode in between.

ContentLicense: CC BY-SA 4.0

Body:
You are looking for

`[v`]

'[ and '] are marks automatically set by vim to the start and the end of the "previously changed or yanked text". v switches to visual mode in between.


问:
Single result from two group Regular Expression?
I would like to take single value from the following strings(HTML tag).

```<code><input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:0" value="6857842162548399092:-3372646398158034589" autocomplete="off" />
</code>```

OR

```<code><update id="j_id1:javax.faces.ViewState:0"><![CDATA[9028765775789786807:-4669779095536779687]]></update>
</code>```

For <input> tag, the expression is

```<code><input type="hidden" name="javax\.faces\.ViewState" id=".*\:javax.faces.ViewState\:.*" value="[^"]+".*\/>
</code>```

For <update> tag, the expression is

```<code><update .*><!\[CDATA\[(.*?.*)\]\]><\/update>
</code>```

In need single result 685784..89 or 90287..87.

The expression have to get single result for <input ...> or <update....>.

答:
You can combine the two with an |("OR").

Assuming the PCRE regex flavour:

```<code>(?|(?:<input type="hidden" name="javax\.faces\.ViewState" id=".*\:javax.faces.ViewState\:.*" value="(?<value>[^"]+)".*\/>)|(?:<update .*?><!\[CDATA\[(?<value>.*?)\]\]><\/update>))
</code>```

Explanation

Body:
I would like to take single value from the following strings(HTML tag).

<input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:0" value="6857842162548399092:-3372646398158034589" autocomplete="off" />

OR

<update id="j_id1:javax.faces.ViewState:0"><![CDATA[9028765775789786807:-4669779095536779687]]></update>

For <input> tag, the expression is

<input type="hidden" name="javax\.faces\.ViewState" id=".*\:javax.faces.ViewState\:.*" value="[^"]+".*\/>

For <update> tag, the expression is

<update .*><!\[CDATA\[(.*?.*)\]\]><\/update>

In need single result 685784..89 or 90287..87.

The expression have to get single result for <input ...> or <update....>.

Body:
You can combine the two with an |("OR").

Assuming the PCRE regex flavour:

(?|(?:<input type="hidden" name="javax\.faces\.ViewState" id=".*\:javax.faces.ViewState\:.*" value="(?<value>[^"]+)".*\/>)|(?:<update .*?><!\[CDATA\[(?<value>.*?)\]\]><\/update>))

Explanation


问:
TFS query on HTML-field for empty value
I want to get with a wiql query all workitem that have an empty HTML field.
Is there a way to do so?</p>

答:
To query out those work items who have empty HTML field like Description, using the query from TFS web page couldn't do that. There's no operator like "isEmpty or isNotEmpty" to use. Here is a uservoice about your request, and according to it, this feature is under review now.

As a workaround, you could use Excel to filter those work items. Write a simple query and export those work items to Excel. Then use the filter In Excel.

You could also use TFS object model api to get those empty field workitems, here is an example:

```<code>        WorkItemStore workItemStore = teamProjectCollection.GetService<WorkItemStore>();
        string queryString = "Select [State], [Title],[Description] From WorkItems Where [Work Item Type] = 'User Story' and [System.TeamProject] = 'TeamProjectName'";

        // Create and run the query.
        Query query = new Query(workItemStore, queryString);
        WorkItemCollection witCollection = query.RunQuery();

        foreach (WorkItem workItem in witCollection)
        {
            //check if the field is empty
            if(workItem.Fields["Description"].Value.ToString() == string.Empty || workItem.Fields["Description"].Value.ToString() == "")
            {
                Console.WriteLine(workItem.Title);
            }
     }
</code>```

Title: TFS query on HTML-field for empty value

Body:
To query out those work items who have empty HTML field like Description, using the query from TFS web page couldn't do that. There's no operator like "isEmpty or isNotEmpty" to use. Here is a uservoice about your request, and according to it, this feature is under review now.

As a workaround, you could use Excel to filter those work items. Write a simple query and export those work items to Excel. Then use the filter In Excel.

You could also use TFS object model api to get those empty field workitems, here is an example:

        WorkItemStore workItemStore = teamProjectCollection.GetService<WorkItemStore>();
        string queryString = "Select [State], [Title],[Description] From WorkItems Where [Work Item Type] = 'User Story' and [System.TeamProject] = 'TeamProjectName'";

        // Create and run the query.
        Query query = new Query(workItemStore, queryString);
        WorkItemCollection witCollection = query.RunQuery();

        foreach (WorkItem workItem in witCollection)
        {
            //check if the field is empty
            if(workItem.Fields["Description"].Value.ToString() == string.Empty || workItem.Fields["Description"].Value.ToString() == "")
            {
                Console.WriteLine(workItem.Title);
            }
     }


问:
Set android.max_aspect to unlimited?
I see that new guidance is to set a value for android.max_aspect in your Manifest.

Is it possible to set this to unlimited (without relying on a kludge like setting it to 9999999, and without setting android:resizeableActivity to true)?

答:
For all practical purposes, you don't need unlimited - it would be sufficient if you set it to a reasonably high value like 10

As you might know, aspect ratio is the ratio of longer side of your display to the other side. If you think about it logically, a display with aspect ratio of 10 itself (width is 10 times height or vice versa) is going to be extremely inconvenient and impractical to design in an android device (imagine viewing your app on a device with a length of 10 times the width!)

As a side, it's poor design to even set the max_aspect to 10 - it would be difficult to test how your app behaves in a 10 aspect ratio device and you can never guess what would go wrong in UI at such extremes.

Title: Set android.max_aspect to unlimited?


问:
how to save all data of listview in text format on button click
```<code><TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:textColor="#000000"
    android:textSize="20sp"/>
</code>```

<p>i am new in android programming please guys help me.That how to save all data of Listview in text format on button click in our mobile </p>

```<code> static String[] city = {"Indore","Bhopal","Mumbai","Pune","Delhi","Kolkata",
        "Hyderabad","Banglore","Chennai","Amritsar","jhalandhar"};

Button button;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    listView = (ListView) findViewById(R.id.lv);

    MyAdapter myadapter = new MyAdapter(getApplicationContext(),city);
    listView.setAdapter(myadapter);
</code>```

答:
Write this code on your button's click

```<code>try {
        File myFile = new File("/sdcard/mysdfile.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter =
                new OutputStreamWriter(fOut);
        for (int i = 0; i < city.length; i++) {
            myOutWriter.append(city[i] +"\n");
        }

        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(),
                "Done writing SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }
</code>```

Note : Don't forget to give below permission in AndroidMenifest.xml

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Body:
<TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:textColor="#000000"
    android:textSize="20sp"/>

i am new in android programming please guys help me.That how to save all data of Listview in text format on button click in our mobile

 static String[] city = {"Indore","Bhopal","Mumbai","Pune","Delhi","Kolkata",
        "Hyderabad","Banglore","Chennai","Amritsar","jhalandhar"};

Button button;
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);
    listView = (ListView) findViewById(R.id.lv);

    MyAdapter myadapter = new MyAdapter(getApplicationContext(),city);
    listView.setAdapter(myadapter);

Body:
Write this code on your button's click

try {
        File myFile = new File("/sdcard/mysdfile.txt");
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter =
                new OutputStreamWriter(fOut);
        for (int i = 0; i < city.length; i++) {
            myOutWriter.append(city[i] +"\n");
        }

        myOutWriter.close();
        fOut.close();
        Toast.makeText(getBaseContext(),
                "Done writing SD 'mysdfile.txt'",
                Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }

Note : Don't forget to give below permission in AndroidMenifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


问:
video capture card (webcam like) with OpenCV
I want to use video capture card to capture my screen display, and process the image by OpenCV/C++.

I have heard that there's some video capture card which is webcam like.(i.e. I can get the screen display by VideoCapture in OpenCV.)

Can someone tell me which video capture card should I buy?

Thanks !!!

答:
I do not know if there some way to achieve that directly using OpenCV. However, a simple workaround could be like this:

Using this software you can create new webcam that stream your screen: https://sparkosoft.com/how-to-stream-desktop-as-webcam-video

Using OpenCV you can start capture the stream using this code:

```<code>cv::VideoCapture cap;
if(!cap.open(0)) // Use the new webcam Id instead of 0
    return 0;
while(true){
      cv::Mat frame;
      cap >> frame;
      if(frame.empty()) break;
      cv::imshow("Screen", frame);
      if( waitKey(10) == 27 ) break;
}
return 0;
</code>```

Body:
I do not know if there some way to achieve that directly using OpenCV. However, a simple workaround could be like this:

Using this software you can create new webcam that stream your screen: https://sparkosoft.com/how-to-stream-desktop-as-webcam-video

Using OpenCV you can start capture the stream using this code:

cv::VideoCapture cap;
if(!cap.open(0)) // Use the new webcam Id instead of 0
    return 0;
while(true){
      cv::Mat frame;
      cap >> frame;
      if(frame.empty()) break;
      cv::imshow("Screen", frame);
      if( waitKey(10) == 27 ) break;
}
return 0;


问:
Table squashing to fit (css)
If I put a table that naturally would be 800px wide in a div that is 700px wide, even with the css property overflow:scroll; set, the table is still 'squashed' into the the 700px space.

Is there any html or css I can edit/re-architect to fix this?

答:
check this may resolve issue </p>

```<code>table
{
table-layout:fixed;
}
</code>```

Title: Table squashing to fit (css)

Body:
check this may resolve issue

table
{
table-layout:fixed;
}


问:
Yii Framework 2.0 $model->validate always returns true
I'm new to the yii2 framework.I cant understand where i did the mistake.Below is my code.

```<code>public function rules()
    {
        return [
            // username and password are both required
            [['oldpassword', 'newpassword','reenternewpassword'], 'required'],
            // rememberMe must be a boolean value
            ['reenternewpassword', 'compare','compareAttribute'=>'newpassword'],
            // password is validated by validatePassword()
            ['oldpassword', 'validatePassword'],
        ];
    }

public function validatePassword()
    {

        $this->password_hash= User::findOne(['username'=>Yii::$app->user->identity->username,'status'=> User::STATUS_ACTIVE])->password_hash;
        if(is_null($this->oldpassword))
            return false;
        return Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash);
    }
</code>```

Model:

```<code>public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validate()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}
</code>```

Here validatePassword is returning false but model validate function is returning true.How?Please help me.

答:
Modify function validatePassword to:

```<code>public function validatePassword($attribute)
        {

            $this->password_hash= User::findOne([
                 'username' => Yii::$app->user->identity->username,
                 'status'=> User::STATUS_ACTIVE
                ])->password_hash;
            if(is_null($this->oldpassword)) {
                    $this->addError($attribute, \Yii::t('app', 'Wrong message');
            }
            if(!Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash)) {
                    $this->addError($attribute, \Yii::t('app', 'Wrong message');
            }
        }
</code>```

Btw, you don't check if User exists, which can throw Exception in this validator.

Body:
I'm new to the yii2 framework.I cant understand where i did the mistake.Below is my code.

public function rules()
    {
        return [
            // username and password are both required
            [['oldpassword', 'newpassword','reenternewpassword'], 'required'],
            // rememberMe must be a boolean value
            ['reenternewpassword', 'compare','compareAttribute'=>'newpassword'],
            // password is validated by validatePassword()
            ['oldpassword', 'validatePassword'],
        ];
    }

public function validatePassword()
    {

        $this->password_hash= User::findOne(['username'=>Yii::$app->user->identity->username,'status'=> User::STATUS_ACTIVE])->password_hash;
        if(is_null($this->oldpassword))
            return false;
        return Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash);
    }

Model:

public function actionChangepwd()
{
if($model->load(Yii::$app->request->post()))
        {
            if($model->validate()){
             echo 'pwd correct';
            }
            else
            {
             echo 'pwd incorrect';
            }
        }
}

Here validatePassword is returning false but model validate function is returning true.How?Please help me.

Body:
Modify function validatePassword to:

public function validatePassword($attribute)
        {

            $this->password_hash= User::findOne([
                 'username' => Yii::$app->user->identity->username,
                 'status'=> User::STATUS_ACTIVE
                ])->password_hash;
            if(is_null($this->oldpassword)) {
                    $this->addError($attribute, \Yii::t('app', 'Wrong message');
            }
            if(!Yii::$app->getSecurity()->validatePassword($this->oldpassword, $this->password_hash)) {
                    $this->addError($attribute, \Yii::t('app', 'Wrong message');
            }
        }

Btw, you don't check if User exists, which can throw Exception in this validator.


问:
Convert a dictionary of lists into a list of dictionaries
I have the following Dictionary Object:

```<code>Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}
</code>```

Which will then result in this specific output:

```<code>output = [{'UserName':'ps_api@auto-grid.com','password': 'Eversource2016!'},
          {'userName':'ps_api1@auto-grid.com','password':'Eversource2016!'}]
</code>```

I'm not sure how I would approach this problem and any help would be appreciated.

答:
And if by chance you need a variable number of keys, you can generalize to:

Code:

```<code>keys = [(k,) * len(data[k]) for k in data.keys()]
data_vals = [data[k] for k in data.keys()]
output = [dict(kv) for kv in
          (zip(*pairs) for pairs in zip(zip(*keys), zip(*data_vals)))]
</code>```

Test Code:

```<code>data = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

for i in output:
    print(i)
</code>```

Output:

```<code>{'userName': 'psrr_api@auto-grid.com', 'password': 'Everseeource2016!'}
{'userName': 'ps_api1@auto-grid.com', 'password': 'Eversource2016!'}
</code>```

Body:
I have the following Dictionary Object:

Input = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

Which will then result in this specific output:

output = [{'UserName':'ps_api@auto-grid.com','password': 'Eversource2016!'},
          {'userName':'ps_api1@auto-grid.com','password':'Eversource2016!'}]

I'm not sure how I would approach this problem and any help would be appreciated.

Body:
And if by chance you need a variable number of keys, you can generalize to:

Code:

keys = [(k,) * len(data[k]) for k in data.keys()]
data_vals = [data[k] for k in data.keys()]
output = [dict(kv) for kv in
          (zip(*pairs) for pairs in zip(zip(*keys), zip(*data_vals)))]

Test Code:

data = {'userName': ['psrr_api@auto-grid.com', 'ps_api1@auto-grid.com'],
         'password': ['Everseeource2016!', 'Eversource2016!']}

for i in output:
    print(i)

Output:

{'userName': 'psrr_api@auto-grid.com', 'password': 'Everseeource2016!'}
{'userName': 'ps_api1@auto-grid.com', 'password': 'Eversource2016!'}


答:
Change your refreshControl code to:

```<code>refreshControl.addTarget(self, action: #selector(NowPlayingViewController.getMovies(_:)), for: .valueChanged)
</code>```

And your function

```<code>func getMovies(_ sender: UIRefreshControl) {
   ...
   sender.endRefreshing()
}
</code>```

Title: passing a closure to addTarget in Swift

Body:
I have a method that gets movies from an api and then loads the data into the UITableView.  I want to reuse the network calls for a refresh control and at the end of the http get request, to call a completion handler that basically stops the refresh control once it's successful.  Is that possible?

func getMovies(completion: (() -> ())?) {
    SVProgressHUD.show()
    Alamofire.request("https://api.moviesite").responseJSON {
        response in
        switch response.result {
        case .success(let data):
            if let json = data as? NSDictionary {
                self.movieResults = json["results"] as! [NSDictionary]
                self.nowPlayingTableView.reloadData()
            }
        case .failure(let error):
            print(error)
            self.showNetworkError(show: true)
        }

        SVProgressHUD.dismiss()
        if completion != nil {
            completion!()
        }
    }
}

And when I use this method in viewDidLoad, I'd like to do something like this:

let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(NowPlayingViewController.getMovies(refreshControl.endRefreshing)), for: .valueChanged)
        nowPlayingTableView.insertSubview(refreshControl, at: 0)

but I get a compiler error about

getMovies cannot be used, did you mean to use a value type instead?

Body:
Change your refreshControl code to:

refreshControl.addTarget(self, action: #selector(NowPlayingViewController.getMovies(_:)), for: .valueChanged)

And your function

func getMovies(_ sender: UIRefreshControl) {
   ...
   sender.endRefreshing()
}


问:
Check Position which hold ID in RecyclerView
I am doing chat Application. I want to put newly coming message item in top position of RecyclerView.For this, I want to match coming Id with all Id which are stored in ArrayList in particular position. How Can I search ID with position in My code. Please some idea.
My code is below </p>

```<code> @Override
public void onBindViewHolder(ChatViewHolder holder, final int position) {

    if (chatList.get(position).modelType == ChatMasterModel.TYPE_USER) {
        try {
            final ChatUserModel userModel = (ChatUserModel) chatList.get(position).modelObj;

            holder.tvBuddyName.setText(userModel.getUserName() + " " + userModel.getUserLastName());
            final String complete_name = userModel.getUserName() + " " + userModel.getUserLastName();
            new ImageLoader(activity).DisplayImage(userModel.getUser_image(), holder.ivChatProfilePic, R.drawable.person_icon);

            holder.chatBuddyList.llChatBuddyItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, ChatBuddtDetailsActivity.class);
                    intent.putExtra("user_id", userModel.getUserId());
                    intent.putExtra("header_name", complete_name);
                    intent.putExtra("user_image", userModel.getUser_image());
                    activity.startActivity(intent);
                }
            });

        } catch (Exception e) {
        }
    } else if (chatList.get(position).modelType == ChatMasterModel.TYPE_GROUP) {
        try {
            final ChatGroupModel groupModel = (ChatGroupModel) chatList.get(position).modelObj;
            new ImageLoader(activity).DisplayImage(groupModel.getGroup_iamge(), holder.ivChatProfilePic, R.drawable.person_icon);
            holder.tvBuddyName.setText(groupModel.getGroupMembers());

           /* if (msg_from.contains(groupModel.getGroupMemberId())) {
                Toast.makeText(activity, "Group contains ID", Toast.LENGTH_SHORT).show();
            }*/

            holder.chatBuddyList.llChatBuddyItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, ChatBuddtDetailsActivity.class);
                    intent.putExtra("group_id", groupModel.getGroup_id());
                    intent.putExtra("group_member_id", groupModel.getGroupMemberId());
                    intent.putExtra("header_name", groupModel.getGroupMembers());
                    intent.putExtra("user_image", groupModel.getGroup_iamge());
                    activity.startActivity(intent);
                }
            });

        } catch (Exception e) {
        }
    }
}

@Override
public int getItemCount() {
    return chatList.size();
}

@Override
public int getItemViewType(int position) {
    return super.getItemViewType(position);
}
</code>```

<p>}</p>

答: store timestamp in arralist and sort array with timestamp and send to recyclerview addafter then notifyadapter</p>

Body:
I am doing chat Application. I want to put newly coming message item in top position of RecyclerView.For this, I want to match coming Id with all Id which are stored in ArrayList in particular position. How Can I search ID with position in My code. Please some idea.
My code is below

 @Override
public void onBindViewHolder(ChatViewHolder holder, final int position) {

    if (chatList.get(position).modelType == ChatMasterModel.TYPE_USER) {
        try {
            final ChatUserModel userModel = (ChatUserModel) chatList.get(position).modelObj;

            holder.tvBuddyName.setText(userModel.getUserName() + " " + userModel.getUserLastName());
            final String complete_name = userModel.getUserName() + " " + userModel.getUserLastName();
            new ImageLoader(activity).DisplayImage(userModel.getUser_image(), holder.ivChatProfilePic, R.drawable.person_icon);

            holder.chatBuddyList.llChatBuddyItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, ChatBuddtDetailsActivity.class);
                    intent.putExtra("user_id", userModel.getUserId());
                    intent.putExtra("header_name", complete_name);
                    intent.putExtra("user_image", userModel.getUser_image());
                    activity.startActivity(intent);
                }
            });

        } catch (Exception e) {
        }
    } else if (chatList.get(position).modelType == ChatMasterModel.TYPE_GROUP) {
        try {
            final ChatGroupModel groupModel = (ChatGroupModel) chatList.get(position).modelObj;
            new ImageLoader(activity).DisplayImage(groupModel.getGroup_iamge(), holder.ivChatProfilePic, R.drawable.person_icon);
            holder.tvBuddyName.setText(groupModel.getGroupMembers());

           /* if (msg_from.contains(groupModel.getGroupMemberId())) {
                Toast.makeText(activity, "Group contains ID", Toast.LENGTH_SHORT).show();
            }*/

            holder.chatBuddyList.llChatBuddyItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, ChatBuddtDetailsActivity.class);
                    intent.putExtra("group_id", groupModel.getGroup_id());
                    intent.putExtra("group_member_id", groupModel.getGroupMemberId());
                    intent.putExtra("header_name", groupModel.getGroupMembers());
                    intent.putExtra("user_image", groupModel.getGroup_iamge());
                    activity.startActivity(intent);
                }
            });

        } catch (Exception e) {
        }
    }
}

@Override
public int getItemCount() {
    return chatList.size();
}

@Override
public int getItemViewType(int position) {
    return super.getItemViewType(position);
}

}