Justin8051
Justin8051

Reputation: 429

WPF: enabling button only if one item in ListBox is selected

I am pretty new to WPF, so forgive me a primitive question. I have researched similar questions on how to enable button only if an item is selected in ListBox through binding, but my condition is a bit more complicated.

  1. The button needs to be disabled if none of the items in ListBox are selected.
  2. The button needs to be enabled if ONE item in Listbox is selected.
  3. The button needs to be disabled if multiple items in Listbox are selected.

In other words, it should be enabled only if user selects ONE item in the ListBox.

What I tried:

<Button Click="EditSingleEntryButton_Click">Edit selected
    <Button.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger 
                    Binding="{Binding ElementName=entriesListBox, Path=SelectedItems.Count}" 
                    Value="0">
                    <Setter Property="Button.IsEnabled" Value="true"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

However, this doesn't work - the button stays enabled all the time.

Upvotes: 0

Views: 421

Answers (1)

EldHasp
EldHasp

Reputation: 7908

You need to add a little bit to your style:

<Button Click="EditSingleEntryButton_Click">Edit selected
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="IsEnabled" Value="False"/>
            <Style.Triggers>
                <DataTrigger 
                    Binding="{Binding ElementName=entriesListBox, Path=SelectedItems.Count}" 
                    Value="1">
                    <Setter Property="IsEnabled" Value="true"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Upvotes: 2

Related Questions