How to enable /disable controls like textbox,label,textblock if combobox is selected/not-selected? e.g. If selected index is greater than zero, enable controls else disable.How to bind IsEnabled properties of the control with combobox selection?
You can bind IsEnabled
to the SelectedIndex
property of the ComboBox and use a IValueConverter
to convert it to Boolean. For instance, in your XAML (showing enabling a Button
):
<ComboBox x:Name="cmbBox" ItemsSource="{Binding Source={StaticResource DataList}}"/>
<Button Grid.Column="1" IsEnabled="{Binding ElementName=cmbBox, Path=SelectedIndex, Converter={StaticResource IndexToBoolConverter}}"/>
Then you need a converter as well, such as:
public class IndexToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((int)value > 0)
{
return true;
}
else
{
return false;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
You'll also have declare the Converter as a resource, such as in your Window.
<local:IndexToBoolConverter x:Key="IndexToBoolConverter"/>
I would probably just do something like this.
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=SelectedItem,
ElementName=TheCombo}"
Value="{x:Null}">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ComboBox x:Name="TheCombo" Width="100">
<ComboBoxItem>Blah</ComboBoxItem>
<ComboBoxItem>Blah</ComboBoxItem>
<ComboBoxItem>Blah</ComboBoxItem>
</ComboBox>
<Button Content="Click Me" Margin="0,10"/>
</StackPanel>
</Grid>
Hope this helps, cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With