tags:

views:

138

answers:

3

Hi, Say I have a WPF XAML code as below

  <Grid>
     <Grid.ColumnDefinition>
       <!--2 Columns are defined-->
     </Grid.ColumnDefinition>

     <Button x:Name="button" Grid.Column="1"/>
     <ListBox x:Name="listBox" Grid.Column="2"/>

  </Grid>

Now, each listboxitems are bound to an object of a class with a member named "Status". Whenever an item is selected, Status becomes "0". If un-selected status becomes "1".

Now, my question is, how do I disable/enable the button (in XAML)whenever any of the items "Status" becomes "0" or "1" respectively. Is there a way to do this via DataTriggers

Thanks

+3  A: 

Could you use the Selection_Changed event handler?

Ardman
+1  A: 

That depends on where this code is. If it is inside a DataTemplate or ControlTemplate you can use a DataTrigger. If not (or even if it is), you should be able to get the same effect with a direct binding. In either case you can use the same basic method. If you create an IValueConverter that takes in listBox's items (collection of your data objects) and outputs a boolean based on the Status values you can use that to bind button's IsEnabled, or check the value in a DataTrigger and disable as needed.

If you're referring to ListBox selection when you say selected/un-selected then the you don't even need to look at the Status values themselves. If you're inside a template (can use Triggers) you could also just check whether listBox has any selected items:

<DataTrigger Binding="{Binding ElementName=listBox, Path=SelectedItems.Count}" Value="0">
    <Setter TargetName="button" Property="IsEnabled" Value="False" />
</DataTrigger>
John Bowen
The problem is I cannot use the SelectedItems.Count property.The reason is, In my case, The listBox datatemplate provides a ToggleButton for Select/Unselect feature (Which Listbox selection does not provide). The toggle button is bound to "Status"So, Is there a way to to access a sibling element(in this case button) from the datatemplate section of the ListBox via DataTrigger?And a question about using valueconverter. Did you mean to set the Datacontext of the button to listbox.Items and Bind it along with a converter?
SysAdmin
A: 

Just be sure to make a corresponding trigger for enabling the button when value is 1. Ardman, you can use the Selection_Changed event handler, but I always try to do as much as possible in the XAML and keep UI alterations out of the code behind. Sometimes it works, every now and then it does not.

Cory

OffApps Cory