views:

69

answers:

2

I have a grid with 2 columns, a listbox in column 0 and a number of other controls in the a secondary grid in the main grids column 1.

I want this controls only to be enabled (or perhaps visible) if an items is selected in the listbox through binding. I tried on a combo box:

IsEnabled="{Binding myList.SelectedIndex}"

But that does not seem to work.

Am I missing something? Should something like this work?

thanks

A: 

Hmm, perhaps it works with a BindingConverter, which converts explicitly all indexes > 0 to true.

DHN
An index of 0 is valid for a ListBox, though. You'd need to do true if > -1.
JustABill
Oh, yes your're right. My fault, thanks.
DHN
+2  A: 

You'll need a ValueConverter for this. This article describes it in detail, but the summary is you need a public class that implements IValueConverter. In the Convert() method, you could do something like this:

if(!(value is int)) return false;
if(value == -1) return false;
return true;

Now, in your XAML, you need to do:

<Window.Resources>
    <local:YourValueConverter x:Key="MyValueConverter">
</Window.Resources>

And finally, modify your binding to:

IsEnabled="{Binding myList.SelectedIndex, Converter={StaticResource MyValueConverter}"

Are you sure you didn't mean

IsEnabled="{Binding ElementName=myList, Path=SelectedIndex, Converter={StaticResource MyValueConverter}"

though? You can't implicitly put the element's name in the path (unless the Window itself is the DataContext, I guess). It might also be easier to bind to SelectedItem and check for not null, but that's really just preference.

Oh, and if you're not familiar with alternate xmlns declarations, up at the top of your Window, add

xmlns:local=

and VS will prompt you for the various possibilities. You need to find the one that matches the namespace you put the valueconverter you made in.

JustABill