Bool Property不会通过Checkbox Binding更新

时间:2016-02-25 07:13:10

标签: c# wpf xaml mvvm binding

在我的WPF MVVM项目(使用MVVM Light)中,我将CheckBox CASE属性绑定到来自我IsChecked中的IsTermsOfUseAccepted属性的bool Property ValidationUserViewModel喜欢这个< / p>

LoginRegisterViewModel

XAML

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;
}

但是我的问题是,除了<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> 属性之外,所有属性绑定到TextBox等等只是工作finde。 我已经尝试手动设置IsTermsOfUseAccept,直接将bool放入RaisePropertyChanged,设置为XAML LoginRegisterViewModelUpdateSourceTrigger=PropertyChanged,但没有任何效果。

可能是什么问题?

1 个答案:

答案 0 :(得分:3)

将IsChecked绑定更改为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

添加?标记