Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable text box when combobox item is selected

I want to enable the text box when comboboxitem is selected . note the combobox item is not defined but rather i have used item source in combox to get the list of combo box items.i want to change the property of a text box when the combox item is selected .

(Comment pasted to original question)

<DataTrigger Binding="{Binding ElementName=cmbInstrumentType,
              Path=SelectedIndex}" 
              Value="1" >
    <Setter Property="IsEnabled" Value="true" />
    <Setter Property="Background" Value="White" /> 
 </DataTrigger>

I want it in XAML only not in code behind. I dont want to repeat that for every index value –

like image 649
user1379584 Avatar asked May 09 '12 10:05

user1379584


2 Answers

Although the better way to do this is to use the MVVM pattern and bind to a property in your ViewModel (as Dabblenl suggested), I think you can achieve what you want like this:

    <StackPanel>
        <ComboBox ItemsSource="{Binding Items}" Name="cmbInstrumentType"/>
        <TextBox>
            <TextBox.Style>
                <Style TargetType="TextBox">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=cmbInstrumentType, Path=SelectedItem}" Value="{x:Null}">
                            <Setter Property="IsEnabled" Value="False"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>
    </StackPanel>

This will disable the textbox if no item is selected in the combobox.

Edit: Expanded code snippet

like image 109
Matt Burland Avatar answered Oct 02 '22 11:10

Matt Burland


i think the best way to do this kind of stuffs is using converters, so you don't have to pollute View with styles that handle that and the logic isn't in the view

something like this

IsEnabled="{Binding ElementName=cboVersion, Path=SelectedItem, Converter={StaticResource ObjectToBoolConverter}}"

of course you need the ObjectToBool coverter, something like this (very simple without type checkings, etc... and should be improved)

public class ObjectToBoolConverter : IValueConverter {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
     return value != null;
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
     throw new NotImplementedException();
  }

}

and remember to register the converter in your resourcedictionary e.g.

<Converters:ObjectToBoolConverter x:Key="ObjectToBoolConverter"/>
like image 40
Not Important Avatar answered Oct 02 '22 10:10

Not Important