Search code examples
wpfbindingcommandcanexecute

How to activate command in dependence of changed property


I have two buttons in my WPF-(popup)control.
First is a Cancel-button, that simply closes the popup and is always enabled.

The second is the Ok-button, that should only be enabled if one of the three (bound) textboxes are changed.

The problem is, that the value of the bound property isn't changed before the textbox has lost focus. So the button isn't active til then and so it isn't clickable, using the mouse.

    <TextBox x:Name="tbFunction" Text="{Binding FunctionSign}" Grid.Column="1" Grid.Row="1" VerticalContentAlignment="Center" Margin="2" Padding="10 0 0 0"/>
    <TextBox x:Name="tbSpecs" Text="{Binding Specs}" Grid.Column="1" Grid.Row="1" VerticalContentAlignment="Center" Margin="2" Padding="10 0 0 0"/>
    <TextBox x:Name="tbSupplement" Text="{Binding Supplement}" Grid.Column="1" Grid.Row="1" VerticalContentAlignment="Center" Margin="2" Padding="10 0 0 0"/>

    <!-- Footer -->
    <Border Grid.Row="3" Padding="{Binding InnerContentPadding}">
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Style="{StaticResource OkCancelButton}" Command="{Binding CloseCommand}" Content="Abbrechen"/>
            <Button Style="{StaticResource OkCancelButton}" Command="{Binding AddressChangedCommand}" Content="Ok"/>
        </StackPanel>
    </Border>

The responsible viewmodel-code:

    //Private Members
    private bool mPropertiesChanged = false;
    private string mFunctionSign;
    private string mSpecs;
    private string mSupplement;


    //the canExecute-method
    private bool SelectionChanged(object paramer)
    {
        return mPropertiesChanged;
    }

    //Public Properties
    public string FunctionSign
    {
        get
        {
            return mFunctionSign;
        }
        set
        {
            mFunctionSign = value;
            mPropertiesChanged = true;
            OnPropertyChanged(nameof(FunctionSign));
        }
    }
    public string Specs
    {
        get
        {
            return mSpecs;
        }
        set
        {
            mSpecs = value;
            mPropertiesChanged = true;
            OnPropertyChanged(nameof(Specs));
        }
    }
    public string Supplement
    {
        get
        {
            return mSupplement;
        }
        set
        {
            mSupplement = value;
            mPropertiesChanged = true;
            OnPropertyChanged(nameof(Supplement));
        }
    }

As one of the Properties is changed and the corresponding textbos looses focus, everything works fine.

Is there a way to get this mPropertiesChanged to true, while the textbos still has focus?


Solution

  • Set the UpdateSourceTrigger of the binding(s) to PropertyChanged:

    Text="{Binding FunctionSign, UpdateSourceTrigger=PropertyChanged}"
    

    This will cause the source property to get set for each key stroke. The default value is LostFocus.