Include text box when combo box is selected

I want to include a text box when comboboxitem is selected. note that the combobox element is not defined, but I used the source of the element in combox to get a list of combo box.i elements to change the text box property when the combox element is selected.

(Comment added 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 this in XAML just not in code. I do not want to repeat that for each index value -

+4
source share
2 answers

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

  <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 text box if no item is selected in the drop-down list.

Edit: Expanded code snippet

+7
source

I think the best way to do such things is to use converters, so you don't need to foul the view with styles that handle it, and the logic is not in the view

something like that

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

of course you need ObjectToBool coverage, something like this (very simple without type checks 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 do not forget to register the converter in your resource for example.

 <Converters:ObjectToBoolConverter x:Key="ObjectToBoolConverter"/> 
+2
source

Source: https://habr.com/ru/post/1411492/


All Articles