我有开关。当我点击那个开关时,我捕捉到false真正或价值。但是当我捕捉到true我想禁用或对我的部门条目做类似的事情,但我没有"处理"。到那个分量。如何在MVVM模式中做到这一点,如何获得一个"处理";到那个组件?因为在代码后面这很简单。对不起,我的英语不好。
internal class RegisterPageViewModel : INotifyPropertyChanged
{
private string _name;
private string _switchValue;
public string Name
{
get => _name;
set
{
_name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
public string SwitchValue
{
get => _switchValue;
set => _switchValue = value;
}
public string MiddleName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string DepartmentCode { get; set; }
public ICommand ImAnEmployeeCommand { get; }
public RegisterPageViewModel()
{
ImAnEmployeeCommand = new Command<bool>(AmAnEmployeeExecute);
}
private void AmAnEmployeeExecute(bool switchValue)
{
if (switchValue)
{
App.Current.MainPage.DisplayAlert("sds", switchValue.ToString(), "dsad");
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
您可以使用数据绑定来实现这一点。
我创建了一个简单的演示并实现了这个功能。
你可以参考下面的代码:
1。为RegisterPageViewModel
添加字段IsChenked
和实现接口INotifyPropertyChanged
:
public class RegisterPageViewModel: INotifyPropertyChanged
{
//add new field here
bool _isChenked;
public bool IsChenked
{
get
{
return _isChenked;
}
set
{
_isChenked = value;
// Do any other stuff you want here
OnPropertyChanged(nameof(IsChenked));
AmAnEmployeeExecute(IsChenked);
}
}
//other code
public string MiddleName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string DepartmentCode { get; set; }
public ICommand ImAnEmployeeCommand { get; }
public RegisterPageViewModel()
{
ImAnEmployeeCommand = new Command<bool>(AmAnEmployeeExecute);
IsChenked = true;
}
private void AmAnEmployeeExecute(bool switchValue)
{
if (switchValue)
{
System.Diagnostics.Debug.WriteLine("switchValue is true");
}
else {
System.Diagnostics.Debug.WriteLine("switchValue is false");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
2。并在YourPage.xaml
中绑定IsChenked
域
<ContentPage.BindingContext>
<formapp619:RegisterPageViewModel></formapp619:RegisterPageViewModel>
</ContentPage.BindingContext>
<StackLayout>
<Entry Placeholder="test" IsVisible="{Binding IsChenked}"/>
<Switch IsToggled="{Binding IsChenked}"/>
</StackLayout>