在我的 WPF MVVM 项目(使用 MVVM Light)中,我将 CheckBox IsChecked 属性绑定(bind)到来自 ValidationUserViewModel 属性的 bool 属性 IsTermsOfUseAccepted
我的 LoginRegisterViewModel
喜欢这个
public interface IValidateUserViewModel
{
// Other Properties..
bool IsTermsOfUseAccepted { get; set; }
bool IsRegistrationValid { get; }
}
public class ValidateUserViewModel : ViewModelBase, IDataErrorInfo, IValidateUserViewModel
{
public bool IsTermsOfUseAccepted
{
get { return _isTermsOfUseAccepted; }
set { Set(ref _isTermsOfUseAccepted, value); }
}
public bool IsRegistrationValid
// IDataErrorInfo Stuff
=> ValidatePropertiesRegistration.All(property => GetValidationError(property) == null)
&& IsTermsOfUseAccepted;
}
// ------------------------------------------------------------------------------------
public class LoginRegisterViewModel : ViewModelBase
{
public LoginRegisterViewModel(
IValidateUserViewModel validateUserViewModel,
IUserRepository userRepository)
{
_userRepository = userRepository;
ValidateUserViewModel = validateUserViewModel;
RegisterCommand = new RelayCommand(RegisterExecute, RegisterCanExecute);
}
public IValidateUserViewModel ValidateUserViewModel
{
get { return _validateUserViewModel; }
set { Set(ref _validateUserViewModel, value); }
}
// RegisterCommand Stuff
public bool RegisterCanExecute() => ValidateUserViewModel.IsRegistrationValid;
}
XAML
<UserControl x:Class="Messenger4u.View.LoginRegisterView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control="clr-namespace:Messenger4u.View.Control"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:metro="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
DataContext="{Binding LoginRegister,
Source={StaticResource Locator}}"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<!-- Stuff -->
<CheckBox IsChecked="{Binding ValidateUserViewModel.IsTermsOfUseAccepted}" />
<!-- Stuff -->
</UserControl>
但我的问题是,除了 IsTermsOfUseAccept
属性之外,绑定(bind)到 TextBoxes 等的所有属性都可以正常工作。
我已经尝试手动设置 RaisePropertyChanged
,直接将 bool 放入 LoginRegisterViewModel
中,在 XAML UpdateSourceTrigger=PropertyChanged
和 Mode=TwoWay 中设置
,但没有任何效果。
可能是什么问题?
最佳答案
将 IsChecked 绑定(bind)更改为 TwoWay 并将 UpdateSourceTrigger 设置为显式:
<CheckBox IsChecked="{Binding ValidateUserViewModel.IsTermsOfUseAccepted, Mode=TwoWay, UpdateSourceTrigger=Explicit}" />
并更改此:
public bool IsTermsOfUseAccepted
致:
bool? _isTermsOfUseAccepted = false; // or true, if you like
public bool? IsTermsOfUseAccepted
添加?
标记
关于c# - Bool 属性不会通过复选框绑定(bind)更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35620677/