35

I have a rather classic UI situation - two ListBoxes named SelectedItems and AvailableItems - the idea being that the items you have already selected live in SelectedItems, while the items that are available for adding to SelectedItems (i.e. every item that isn't already in there) live in AvailableItems.

Also, I have the < and > buttons to move the current selection from one list to the other (in addition to double clicking, which works fine).

Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? SelectedItems is on the left side, so the < button will move the selected AvailableItems to that list. However, if no items are selected (AvailableItems.SelectedIndex == -1), I want this button to be disabled (IsEnabled == false) - and the other way around for the other list/button.

Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it?

2
  • 2
    if by fun you mean utterly, utterly horrible, the-only-way-to-make-it-worse-would-be-with-regex, then yeah its great fun Commented Jun 3, 2010 at 17:01
  • 1
    @Will That's a good analogy because I would love to smash nuts with a rubber mallet Commented May 30, 2013 at 21:56

3 Answers 3

84

Less code solution:

<Button Name="button1" IsEnabled="{Binding ElementName=listBox1, Path=SelectedItems.Count}" />

If count is 0 that seems to map to false, > 0 to true.

Sign up to request clarification or add additional context in comments.

2 Comments

the nice thing about the other answer is, you can use it for 2 lists, both have to have something selected to enable the button.
this is only if the listview has at least one items , the question is enable button when the item was selected.
56

Here's your solution.

<Button Name="btn1" >click me    
    <Button.Style>        
        <Style>            
            <Style.Triggers>                
                <DataTrigger 
                     Binding ="{Binding ElementName=list1, Path=SelectedIndex}" 
                     Value="-1">                    
                    <Setter Property="Button.IsEnabled" Value="false"/>                    
                </DataTrigger>                
            </Style.Triggers>            
        </Style>        
    </Button.Style>    
</Button>

Comments

0
 <Button IsEnabled="{Binding SelectedValue, ElementName=ListName, Mode=OneWay, TargetNullValue=0}" >Remove</Button>

that worked in my case

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.