How can I change BackgroundColor of CustomLabel in Selected Action State Event CreateCustomLableNavigationState method Similar to ListviewItemSelection Event

G, S 0 Reputation points
2024-05-30T14:41:47.06+00:00
            <ListView  x:Name="listView" ItemsSource="{Binding ItemList}"  RowHeight="43" Margin="0,-5,0,0" CachingStrategy="RecycleElement">

                <ListView.ItemTemplate>

                    <DataTemplate>

                        <ViewCell>

                                <Grid x:Name="grid" RowSpacing="0" ColumnSpacing="0" RowDefinitions="44, Auto" ColumnDefinitions="170,Auto,90,Auto,90,Auto,90,Auto,90,Auto,90,Auto">

                                <local:CustomLable x:Name="meassurementColLabel" ClassId="{Binding Index}" ColumnIndex="0" LongPressed="Listitemlongpress" Text="{Binding MeasurementLable}" Grid.Row="0" Grid.Column="0" 

                                                  

                                                       BackgroundColor="White"

                                                   Style="{StaticResource CustomLableHighlightStyle}" IsSelected="False"

                                                   >

                                    </local:CustomLable>

									

									

                                    <BoxView Grid.Row="0"  Grid.Column="1" WidthRequest="1" BackgroundColor="LightGray"></BoxView>

                                <local:CustomLable x:Name="valueColLabel" ClassId="{Binding Index}" ColumnIndex="1" LongPressed="Listitemlongpress" Text="{Binding Value}"   Grid.Row="0" Grid.Column="2" 

                                                       HorizontalTextAlignment="Center" VerticalTextAlignment="Center"

                                                       BackgroundColor="{Binding ParameterStatus, Converter={StaticResource valueStatusToColor}, ConverterParameter={x:Reference valueColLabel}}"

                                                       FontAttributes="None" FontSize="17" TextColor="White" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Padding="0" IsSelected="False">

                                        <local:CustomLable.Triggers>

                                            <Trigger TargetType="local:CustomLable" Property="BackgroundColor" Value="Red">

                                                <Setter Property="TextColor" Value="White" />

                                            </Trigger>

                                            <Trigger TargetType="local:CustomLable" Property="BackgroundColor" Value="Orange">

                                                <Setter Property="TextColor" Value="White" />

                                            </Trigger>

                                            <Trigger TargetType="local:CustomLable" Property="BackgroundColor" Value="SkyBlue">

                                                <Setter Property="TextColor" Value="White" />

                                            </Trigger>

                                            <Trigger TargetType="local:CustomLable" Property="BackgroundColor" Value="White">

                                                <Setter Property="TextColor" Value="Black" />

                                            </Trigger>

                                        </local:CustomLable.Triggers>

                                    </local:CustomLable>

                                    <BoxView Grid.Row="0"  Grid.Column="3" WidthRequest="1" BackgroundColor="LightGray"></BoxView>

                                <local:CustomLable ClassId="{Binding Index}" ColumnIndex="2" LongPressed="Listitemlongpress" Text="{Binding Min}" Grid.Row="0" Grid.Column="4" FontAttributes="None" FontSize="17" TextColor="Black" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"  Padding="0"

                                                       HorizontalTextAlignment="Center" VerticalTextAlignment="Center"

                                                       BackgroundColor="White"

                                                   Style="{StaticResource CustomLableHighlightStyle}" IsSelected="False"

                                                   >

                                    </local:CustomLable>

                                    <BoxView Grid.Row="0"  Grid.Column="5" WidthRequest="1" BackgroundColor="LightGray"></BoxView>

                                <local:CustomLable ClassId="{Binding Index}" ColumnIndex="3" LongPressed="Listitemlongpress" Text="{Binding Max}" Grid.Row="0" Grid.Column="6" BackgroundColor="White"  FontAttributes="None" FontSize="17" TextColor="Black" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"   Padding="0"

                                                       HorizontalTextAlignment="Center" VerticalTextAlignment="Center"

                                                       Style="{StaticResource CustomLableHighlightStyle}" IsSelected="False"

                                                       IsVisible="{Binding IsShowMinMaxAvg}"></local:CustomLable>

                                    <BoxView Grid.Row="0"  Grid.Column="7" WidthRequest="1" BackgroundColor="LightGray" IsVisible="{Binding IsShowMinMaxAvg}"></BoxView>

                                <local:CustomLable ClassId="{Binding Index}" ColumnIndex="4" LongPressed="Listitemlongpress" Text="{Binding Avg}" Grid.Row="0" Grid.Column="8" BackgroundColor="White"  FontAttributes="None" FontSize="17" TextColor="Black"  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Padding="0"

                                                       HorizontalTextAlignment="Center" VerticalTextAlignment="Center"

                                                       Style="{StaticResource CustomLableHighlightStyle}" IsSelected="False"

                                                       IsVisible="{Binding IsShowMinMaxAvg}"></local:CustomLable>

                                    <BoxView Grid.Row="0"  Grid.Column="9" WidthRequest="1" BackgroundColor="LightGray" IsVisible="{Binding IsShowMinMaxAvg}"></BoxView>

                                <local:CustomLable ClassId="{Binding Index}" ColumnIndex="5" LongPressed="Listitemlongpress" Text="{Binding Unit}"  Grid.Row="0" Grid.Column="10" BackgroundColor="White"  FontAttributes="None" FontSize="17" TextColor="Black"  VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"   Padding="0"

                                                       HorizontalTextAlignment="Center" VerticalTextAlignment="Center"

                                                       Style="{StaticResource CustomLableHighlightStyle}" IsSelected="False"

                                                       IsVisible="{Binding IsShowMinMaxAvg}"></local:CustomLable>

                                    <BoxView Grid.Row="0"  Grid.Column="11" WidthRequest="1" BackgroundColor="LightGray" IsVisible="{Binding IsShowMinMaxAvg}"></BoxView>

                                    <BoxView Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="12" HeightRequest="1" BackgroundColor="LightGray" IsVisible="{Binding IsShowMinMaxAvg}"></BoxView>

                                </Grid>

                        </ViewCell>

                    </DataTemplate>

                </ListView.ItemTemplate>

            </ListView>

			

			        private HardKeyNavigationState CreateCustomLableNavigationState(View view, int rowIndex, int columnIndex, ObservableCollection<DetailPageModel> itemList_obj)

    {

        // creates new navigation state for list item

        HardKeyNavigationState navigationState = new HardKeyNavigationState($"Cell-Row{rowIndex}-Column{columnIndex}")

        {

            Selected = () =>

            {

                Device.BeginInvokeOnMainThread(() =>

                {

                    CustomLable customLabel = view as CustomLable;

                    int r = rowIndex;

                    int c = columnIndex;

                    CustomLable targetLabel = FindCustomLable(rowIndex, columnIndex);

                    if (targetLabel != null)

                    {

                    }

;

                });

            },

            Unselected = () =>

            {

                Device.BeginInvokeOnMainThread(() =>

                {

                    CustomLable targetLabel = FindCustomLable(rowIndex, columnIndex);

                    if (targetLabel != null)

                    {

                    }

                });

            }

        };

        // handling of 'Enter' hard key pressed for this state

        navigationState.EnterPressed = () =>

        {

            Listitemlongpress(view as CustomLable, null);

            return navigationState;

        };

        return navigationState;

    }

    private CustomLable FindCustomLable(int classId, int columnIndex)

    {

        View listViewItem = (listView.TemplatedItems[classId] as ViewCell).View;

        Grid grid = listViewItem as Grid;

        foreach (var child in grid.Children)

        {

            if (child is CustomLable customLabel)

            {

                if (customLabel.ClassId == classId.ToString() && customLabel.ColumnIndex == columnIndex)

                {

                    return customLabel;

                }

            }

        }

        return null;

    }

	

	    public class DetailPageModel : BaseViewModel

{

    private int columnIndex;

    public int Index { get; set; }

    public string MeasurementLable { get; set; }

    public string MeasurementRange { get; set; }

    public string Value { get; set; }

    public string Min { get; set; }

    public string Max { get; set; }

    public string Avg { get; set; }

    public string Unit { get; set; }

    public string ParameterStatus { get; set; }

    public bool IsShowMinMaxAvg { get; set; }

    public int ColumnIndex

    {

        get

        {

            return columnIndex;

        }

        set

        {

            columnIndex = value;

            OnPropertyChanged();

        }

    }
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,362 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
814 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 43,841 Reputation points Microsoft Vendor
    2024-05-31T05:58:18.93+00:00

    Hello,

    You can do this with data binding and ValueConverter. Please refer to the steps and documentation below.

    Step 1. Add a bool attribute to the model class to mark whether this Item is selected or not.

    
    public class Item : INotifyPropertyChanged
    
    {
    
        public string Id { get; set; }
    
        public string Text { get; set; }
    
        public string Description { get; set; }
    
     
    
        private bool isSelected { get; set; }
    
     
    
        public bool IsSelected
    
        {
    
            get => isSelected;
    
            set
    
            {
    
                isSelected = value;
    
                OnPropertyChanged();
    
            }
    
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
     
    
        public void OnPropertyChanged([CallerMemberName] string name = "") =>
    
       PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    
    }
    
    

    Step 2. Implement ValueConverter to return different colors by whether the item is selected or not.

    
        public class BoolToBrushConverter : IValueConverter
    
        {
    
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    
            {
    
                if ((bool)value == true)
    
                {
    
                    return Color.Red;
    
                }
    
                else
    
                {
    
                    return Color.Green;
    
                }
    
            }
    
     
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    
            {
    
                return (bool)value ? Color.Red : Color.Green;
    
            }
    
        }
    
    

    Step 3. Setting the binding for a Label in ListView

    
    <Label Text="{Binding Description}" 
    
    LineBreakMode="NoWrap"
    
    BackgroundColor="{Binding IsSelected,Converter={StaticResource BoolToBrush}}"
    
    FontSize="13" />
    
    

    Step 4. Since the notification feature was previously implemented in the Item, you can have the ValueConverter automatically change the color when selected and unselected by simply changing the value of IsSelected.

    
    private void ItemsListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
    
    {
    
        var item = e.SelectedItem as Item;
    
        if (item != null)
    
        {
    
            item.IsSelected = true;
    
        }
    
    }
    
    

    Xamarin support ended on May 1, 2024 for all Xamarin SDKs including Xamarin.Forms. For more information, please check: Xamarin official support policy | .NET (microsoft.com). We will recommend you upgrade Xamarin projects to . NET MAUI, please see the Upgrade from Xamarin to .NET & .NET MAUI documentation.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.