Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/Disable controls on ComboBox selection in Xaml

Tags:

wpf

xaml

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?

like image 705
xyz Avatar asked Jun 14 '16 13:06

xyz


2 Answers

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"/>
like image 173
matthew_b Avatar answered Sep 28 '22 09:09

matthew_b


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!

like image 29
Chris W. Avatar answered Sep 28 '22 08:09

Chris W.