У меня есть способ изменить кнопки BackgroundColor
, когда каждая кнопка нажата.Это я могу легко сделать из кода.
Использование метода ниже в каждом событии нажатия кнопки
void ButtonStyle(Button btn)
{
foreach (var button in buttons)
{
if (button.Id == btn.Id)
{
button.BackgroundColor = Color.Blue;
button.BorderColor = Color.Red;
button.TextColor = Color.White;
}
else
{
button.BackgroundColor = Color.White;
button.BorderColor = Color.Gray;
button.TextColor = Color.Blue;
}
}
}
Но когда я использую MVVM для той же задачи,У меня есть огромный код для этого
Часть класса ViewModel кода примера кода.
public class AssignmentDetailViewModel : INotifyPropertyChanged
{
private Color _bgColorBtn1;
private Color _bgColorBtn2;
private Color _bgColorBtn3;
private Color _txtColorBtn1;
private Color _txtColorBtn2;
private Color _txtColorBtn3;
public Color BgColorBtn1
{
get { return _bgColorBtn1; }
set
{
if (value == _bgColorBtn1)
return;
_bgColorBtn1 = value;
}
}
public Color BgColorBtn2
{
get { return _bgColorBtn2; }
set
{
if (value == _bgColorBtn2)
return;
_bgColorBtn2 = value;
}
}
public Color BgColorBtn3
{
get { return _bgColorBtn3; }
set
{
if (value == _bgColorBtn3)
return;
_bgColorBtn3 = value;
}
}
public Color TextColorBtn1
{
get { return _txtColorBtn1; }
set
{
if (value == _txtColorBtn1)
return;
_txtColorBtn1 = value;
}
}
public Color TextColorBtn2
{
get { return _txtColorBtn2; }
set
{
if (value == _txtColorBtn2)
return;
_txtColorBtn1 = value;
}
}
public Color TextColorBtn3
{
get { return _txtColorBtn3; }
set
{
if (value == _txtColorBtn3)
return;
_txtColorBtn1 = value;
}
}
public Command BtnColorsCmd1
{
get
{
return new Command(() => {
_bgColorBtn1 = Color.White;
_txtColorBtn1 = Color.Blue;
});
}
}
public Command BtnColorsCmd2
{
get
{
return new Command(() => {
_bgColorBtn1 = Color.White;
_txtColorBtn1 = Color.Blue;
});
}
}
public Command BtnColorsCmd3
{
get
{
return new Command(() => {
_bgColorBtn1 = Color.White;
_txtColorBtn1 = Color.Blue;
});
}
}
}
xaml file
<StackLayout BackgroundColor="White" Spacing="2.5" VerticalOptions="Start" Padding="7,6,7,3" Orientation="Horizontal" x:Name="stackLayou1">
<Button HorizontalOptions="FillAndExpand" TextColor="{Binding _txtColorBtn1}" BackgroundColor="{Binding _bgColorBtn1}" x:Name="button1" Text="Assignment"></Button>
<Button HorizontalOptions="FillAndExpand" TextColor="{Binding _txtColorBtn2}" BackgroundColor="{Binding _bgColorBtn2}" x:Name="button2" Text="Content"></Button>
<Button HorizontalOptions="FillAndExpand" TextColor="{Binding _txtColorBtn3}" BackgroundColor="{Binding _bgColorBtn3}" x:Name="button3" Text="Review"></Button>
</StackLayout>
Есть ли способ уменьшить этот код или другой способ сделать это?