Search code examples
c#wpfitemscontrolstackpanel

WPF: Disable items in bounded ItemsControl


I'm working on a WPF page with the following:

<ItemsControl ItemsSource="{Binding Peopl.PhoneNums}" x:Name="PhoneList">
 <ItemsControl.ItemTemplate>
   <DataTemplate>
     <Grid>
       <StackPanel Orientation="Horizontal" Margin="0,0,0,0" x:Name="PhoneEntry">
          <TextBlock Text="123-456-78901"/>
          <ComboBox ...>
       </StackPanel>
      </Grid>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
 </ItemsControl>

There can be multiple stackpanels, each with a unique phone number; in code behind, each phone number has a flag indicating if it should be enabled; I want to be able to enable each entry in the stack panel based on that flag but I'm stuck accessing it....

I have:

foreach (Phone phone in PhoneList.ItemsSource)
            {
                if (phone.ShouldBeDisabled)
                {
                    int index = PhoneList.Items.IndexOf(phone);
                    PhoneList.IsEnabled = false; 
                    //this disables the entire control; 

                    // I can't access "PhoneEntry" here... hmm
                }
            }

Is there a way to disable only one entry at a time? How can I access PhoneEntry? Should I try to disable the each stackpanel entry based on the bound value?


Solution

  • You may invert your view model property and call it ShouldBeEnabled. Now you can bind the StackPanel's IsEnabled property.

    <StackPanel ... IsEnabled="{Binding ShouldBeEnabled}">
        ...
    </StackPanel>
    

    In case you can't change the view model, you may use a binding converter that inverts the property value:

    <StackPanel ... IsEnabled="{Binding ShouldBeDisabled,
                                Converter={StaticResource InverseBooleanConverter}}">
        ...
    </StackPanel>
    

    Your Phone class would have to implement the INotifyPropertyChanged interface and fire the PropertyChanged event when the value of the ShouldBeDisabled property changes.