Home > Mobile >  WPF binding foreground color of control to mouse hover
WPF binding foreground color of control to mouse hover

Time:03-16

I have a user control for which I have to change color, based on mouse hover, click or none. Following MVVM. This is the code I have -

User control in XAML

<userControls:NC DataContext="{Binding NCVM}" >
 
                </userControls:NC>

User Control View Model

public class NCVM : ObservableObject
    {

        public NCVM()
        {

        }

        private NCState _currentState = NCState.InActive;
        public NCState CurrentState
        {
            get => _currentState;
            set
            {
                _currentState = value;

                switch (_currentState)
                {
                    case NCState.InActive:
                        ForegroundColor = System.Windows.Media.Brushes.LightGray;
                        IsActive = false;
                        break;
                    case NCState.Active:
                        ForegroundColor = System.Windows.Media.Brushes.White;
                        IsActive = true;
                        break;
                    case NCState.Hovered:
                        ForegroundColor = System.Windows.Media.Brushes.White;
                        IsActive = false;
                        break;
                    default:
                        ForegroundColor = System.Windows.Media.Brushes.LightGray;
                        IsActive = false;
                        break;
                }
            }
        }

        public bool _isActive;
        public bool IsActive
        {
            get => _isActive;
            set => SetProperty(ref _isActive, value);
        }

        private System.Windows.Media.Brush _foregroundColor = System.Windows.Media.Brushes.LightGray;

        public System.Windows.Media.Brush ForegroundColor
        {
            get => _foregroundColor;
            set => SetProperty(ref _foregroundColor, value);
        }


    }

Main Window View Model

Public class MWVM : BVM
    {
        #region Private Variables
        private NCVM _NCVM = new();
        #endregion

        public MWVM()
        {
            NCVM.CurrentState = NCState.Active;
        }

        #region Public Properties
        public NCVM NCVM
        {
            get => _NCVM;
            set => SetProperty(ref _NCVM, value);
        }
        #endregion
    }

Right now, it's getting preset as active for checking. Now, I have to make it manual so it changes on hover, but not getting how to do with binding.

CodePudding user response:

You may take a look at EventTrigger, or Triggers in general to style your control.

*Edit: A little example, MVVM not considered, just for you to get a glimpse at triggers.

UserControl:

<UserControl x:Class="WpfApp1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d" 
             d:DataContext="{d:DesignInstance Type={x:Type local:UserControl1}}"
             Height="200" Width="400">
    <UserControl.Style>
        <Style TargetType="UserControl">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsMyPropSet}" Value="True">
                    <Setter Property="Background" Value="Turquoise"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </UserControl.Style>
    <GroupBox Header="I am your usercontrol">
        <Button Width="100" Height="35" Content="Toggle Property" Click="Button_Click"/>
    </GroupBox>
</UserControl>

and code-behind:

    public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
    public UserControl1()
    {
        InitializeComponent();
        DataContext = this;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public bool IsMyPropSet { get; set; }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        IsMyPropSet = !IsMyPropSet;
        RaisePropertyChanged(nameof(IsMyPropSet));
    }

    protected void RaisePropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

CodePudding user response:

The MVVM pattern is about separating the user interface (view) from the data and application logic itself. Your example violates MVVM in that it stores the brushes and the visual states in a view model. The view model should only expose data and commands to be bound, but not user interface elements and it must not contain logic to that relates to the user interface just like managing visual states or appearance. It is too often misunderstood as creating a view model and just put everything there.

In you case I think that you can solve your issue by moving the everything into a style. The following should show your userControls:NC. There are triggers for different states like Disabled, Hover / Mouse Over. Please note that you need to set a Background, otherwise the control does not participate in hit testing and e.g. the IsMouseOver property will not be True. For no background use Transparent (not equal to unset).

<UserControl ...>
   <UserControl.Style>
      <Style TargetType="{x:Type local:BorderUserControl}">
         <!-- Background must be set at least to "Transparent" -->
         <Setter Property="Background" Value="Black"/>
         <!-- Default -->
         <Setter Property="Foreground" Value="LightGray"/>
         <Style.Triggers>
            <!-- Hovered -->
            <Trigger Property="IsMouseOver" Value="True">
               <Setter Property="Foreground" Value="White"/>
            </Trigger>
            <!-- Disabled -->
            <Trigger Property="IsEnabled" Value="False">
               <Setter Property="Foreground" Value="LightGray"/>
            </Trigger>
         </Style.Triggers>
      </Style>
   </UserControl.Style>

   <!-- Dummy element for demonstration purposes of foreground -->
   <TextBlock Text="This text shows the foreground"/>

</UserControl>
  • Related