Ramesh Soni
Ramesh Soni

Reputation: 16077

Change binded object property on button click in WPF

I have binded an object to a WPF control. How can I toggle the object property "IsEditMode" on click of the edit button using only xaml and no code behind? Here is sample code of xaml -

<Label Style="{StaticResource TitleLabel}" 
       Content="{Binding Path=GroupTitle}" 
       Visibility="{Binding Path=IsEditMode, Converter={StaticResource boolToVis}}"
       HorizontalAlignment="Left" />

<Button Content="Edit" HorizontalAlignment="Right" VerticalAlignment="Center">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <!--Toggle the bindedobject.IsEditMode property of click of button-->
        </EventTrigger>
    </Button.Triggers>
</Button>

Upvotes: 1

Views: 6396

Answers (2)

John Bowen
John Bowen

Reputation: 24453

There's a control for that already in the framework:

<Label Style="{StaticResource TitleLabel}" 
       Content="{Binding Path=GroupTitle}" 
       Visibility="{Binding Path=IsEditMode, Converter={StaticResource boolToVis}}"
       HorizontalAlignment="Left" />

<ToggleButton Content="Edit" HorizontalAlignment="Right" VerticalAlignment="Center"
       IsChecked="{Binding IsEditMode}"/>

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292465

using only xaml and no code behind

I don't think it's possible with no C# (or VB) code at all, but you can do it with no code-behind, using the MVVM pattern. So you will have C# code, just not in the code-behind...

If you go this way, you need to expose a command from your ViewModel:

    private DelegateCommand _enterEditModeCommand;
    public ICommand EnterEditModeCommand
    {
        get
        {
            if (_enterEditModeCommand== null)
            {
                _enterEditModeCommand= new DelegateCommand(EnterEditMode);
            }
            return _enterEditModeCommand;
        }
    }

    private void EnterEditMode()
    {
        IsEditMode = true;
    }

And bind your button to that command:

<Button Content="Edit" Command="{Binding EnterEditModeCommand}"
        HorizontalAlignment="Right" VerticalAlignment="Center">

Upvotes: 2

Related Questions