简体   繁体   中英

MVVMLight: RelayCommand seems not working in Windows 8 App

I have the following ViewModel:

public class TransportationUnit : ViewModelBase {
    private string _TypeOfFuel;
    private string _Model;
    private string _Manufacturer;
    private string _LicencePlate;
    private Guid _Key = Guid.Empty;

    public ICommand CmdAddTransportationUnit { get; set; }

    public TransportationUnit() {
        CmdAddTransportationUnit = new GalaSoft.MvvmLight.Command.RelayCommand( () => AddTransportationUnitDo(), () => AddTransportationUnitCan() );
    }

    /// <summary>manufacturer</summary>
    public string Manufacturer {
          get { return _Manufacturer; }
          set {
            if (_Manufacturer == value )
                return;
            RaisePropertyChanging( "Manufacturer" );
            _Manufacturer = value;
            RaisePropertyChanged( "Manufacturer" );
        }
    }

    /* ommitted some equal properties */

    public bool AddTransportationUnitCan() {
        return !string.IsNullOrWhiteSpace( Model ) && !string.IsNullOrWhiteSpace( Manufacturer ) & !string.IsNullOrWhiteSpace( LicencePlate );
    }

    public async void AddTransportationUnitDo() {
        await LogbookRepository.Instance.Add<TransportationUnit>( this );
    }
}

My textboxes are bound that way:

<TextBox x:Name="CarManufacturerNameText" Width="400" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="0" Grid.Column="1" Text="{Binding Manufacturer,Mode=TwoWay}" />

My button in the AppBar (bottom) is bound that way:

<Button Style="{StaticResource SaveAppBarButtonStyle}" AutomationProperties.Name="" x:Name="save" x:Uid="StandardSave" Command="{Binding CmdAddTransportationUnit}" />

I would have expected that the button is disabled when the method AddTransportationUnitCan evaluates to false and vice versa. When all textboxes are filled, it keeps being disabled, and even a breakpoint set in the method only fires once when the RelayCommand is created. I've tested for a rather long time, but haven't found a solution. Anyone else had this problem?

Edit: When I just return true in AddTransportationUnitCan the button is enabled

Try adding a RaiseCanExecuteChanged to your property setters. This will tell your RelayCommand to reevaluate the CanExecute.

public string Manufacturer {
          get { return _Manufacturer; }
          set {
            _Manufacturer = value;
            RaisePropertyChanged( "Manufacturer" );
            CmdAddTransportationUnit.RaiseCanExecuteChanged(); 
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM