Home > Enterprise >  Problem in Changing the Background color of label on Button Click in MVVM WPF
Problem in Changing the Background color of label on Button Click in MVVM WPF

Time:07-15

While declaring the variable and in constructor I can work on the background color of label using MVVM WPF But on other event like Button Event It's not changing the color.

XAML Code

<Label Content="{Binding MessageArea1Content}" Height="25" Width="830"
       Name="level2LBL" Background="{Binding Path=BrushMessageArea1}" 
       Foreground="White" HorizontalContentAlignment="Center" 
       VerticalContentAlignment="Center" FontWeight="Bold" 
       HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,5,0,0"/>

Code

private Brush _brushMessageArea2 = Brushes.Green;

public Brush BrushMessageArea2
{
    get { return _brushMessageArea2; }
    set { _brushMessageArea2 = value; }
}

public HomeViewModel()
{   
    PutCommand = new DelegateCommand(OnPutCommand);

    BrushMessageArea1 = Brushes.Red; //new SolidColorBrush((Color)ColorConverter.ConvertFromString("Red"));
    
    private async void OnPutCommand()
    {
        BrushMessageArea1 = Brushes.Red; //new SolidColorBrush((Color)ColorConverter.ConvertFromString("Red"));
    }
}

On PUTCommand It's not working.

CodePudding user response:

It's not really clear what BrushMessageArea2 is doing there, as it's neither in the binding or any of the provided methods.

However, assuming that BrushMessageArea1 follows the same format as BrushMessageArea2 (with backing field), then you can update the Brush property in your XAML by adding OnPropertyChanged(nameof(BrushMessageArea1) as follows:

private Brush _brushMessageArea1;

public Brush BrushMessageArea1
{
    get => return _brushMessageArea1;
    set 
    { 
        _brushMessageArea1 = value; 
        OnPropertyChanged(nameof(BrushMessageArea1));
    }
}

However, do note that this method requires that the class you implement this in inherits from INotifyPropertyChanged or a class which inherits from that.

  • Related