vladc77
vladc77

Reputation: 1064

How to set buttons property IsEnabled based if listbox has content in it?

I am trying to make button with property IsEnabled=true only is listbox has one item. If listbox has zero items than button property isEbabled has to be 'false'. I'd like t find what will be the best approach to achieve it. I am ading listboxitems dynamically. Any ideas are highly appreciated!

<ListBox x:Name="ListBox" SelectionMode="Multiple" Height="100" />
<Button x:Name="btnNext" Style="{StaticResource AVV_ButtonStyle}" Content="NextButton" IsEnabled="False" />

Upvotes: 0

Views: 588

Answers (2)

Quintonn
Quintonn

Reputation: 790

You could use a command for the button. Then you can specify the CanExecute method for the command. And this will make to button enabled/disable. Then all you have to do is re-check the CanExecute value every time your listBox's source changes. With code similar to:

        (this as INotifyPropertyChanged).PropertyChanged += (s, e) =>
        {
            (YourCommand as DelegateCommand).RaiseCanExecuteChanged();
        };

Upvotes: 0

benPearce
benPearce

Reputation: 38333

In WPF:

<ListBox x:Name="ListBox" SelectionMode="Multiple" Height="100" />
<Button x:Name="btnNext" Style="{StaticResource AVV_ButtonStyle}" Content="NextButton" IsEnabled="{Binding ElementName=ListBox,Path=HasItems" />

Silverlight does not support HasItems on the ItemsControl so you would need to move this binding to a boolean property on your DataContext, this would return something like:

return list.Count > 0

I would subscribe to the CollectionChanged event on the collection your List is bound to then raise a PropertyChanged event against the boolean property your IsEnabled property is bound to to force the binding to re-read its source.

If you have bound your button to a command you can do this via the CanExecute property on the command, although the Commands implementation in Silverlight differs from WPF.

Upvotes: 2

Related Questions