How can I set a bacground color for button in ViewModel?
I want to set color at start (when page is being opened) and be able to change it later. I just have no idea how to do it right.
Here is code that I doesn't work.
xaml
<ContentPage.BindingContext>
<viewmodels:ChangeColorModeViewModel/>
</ContentPage.BindingContext>
<Button
x:Name="Button1"
Grid.Row="0"
Grid.Column="0"
BackgroundColor="{Binding btnColor}"
Clicked="BtnCheckColor"/>
View model
public partial class ChangeColorModeViewModel : INotifyPropertyChanged
{
public ChangeColorModeViewModel()
{
BtnColor = ColorLose;
}
public static Color BtnColor;
public static Color ColorWin = Color.FromRgb(0, 0, 255);
public static Color ColorLose = Color.FromRgb(0, 0, 0);
public Color btnColor
{
get
{
return BtnColor;
}
set
{
if (value != BtnColor)
{
BtnColor = value;
OnPropertyChanged(nameof(btnColor));
}
}
}
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
CodePudding user response:
As tataelm suggested, just remove the static from public static Color BtnColor;
I tested it and it successfully set a background color(Blue) for button in ViewModel.
Here's the code snippet below for your reference:
public partial class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Color ColorWin = Color.FromRgb(0, 0, 255);
private Color _btnCoior;
public Color btnColor
{
get => _btnCoior;
set
{
_btnCoior = value;
OnPropertyChanged(nameof(_btnCoior));
}
}
public MainPageViewModel()
{
btnColor = ColorWin;
}
#region INotifyPropertyChanged
void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}