【发布时间】:2016-02-25 07:13:09
【问题描述】:
在我的 WPF MVVM 项目(使用 MVVM Light)中,我将 CheckBox IsChecked 属性绑定到我的 ValidationUserViewModel 属性中的 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>
但我的问题是,绑定到 TextBoxes 等的所有属性都只能正常工作,除了 IsTermsOfUseAccept 属性。
我已经尝试手动设置RaisePropertyChanged,将bool直接放入LoginRegisterViewModel,在XAML中设置UpdateSourceTrigger=PropertyChanged和Mode=TwoWay,但没有任何效果。
可能是什么问题?
【问题讨论】:
-
@Sakura 谢谢,这行得通.. 但为什么它必须是一个可空的布尔值?现在 CheckBox ist 填充了一个减号
-默认情况下需要单击两次才能为真..我可以改变它吗? -
因为 CheckBox 有 3 种状态:选中、取消选中和未确定。
-
您必须为
_isTermsOfUseAccepted设置默认值。看我的回答。 -
Snoop 之类的工具对于在运行时检查绑定和数据上下文很有用。