Consider the following combobox:
<ComboBox ItemsSource="{Binding Presets.VolumePresetList}" SelectedIndex="{Binding VolumePresetSelectedIndex, UpdateSourceTrigger=PropertyChanged}" Margin="10, 10" HorizontalAlignment="Left"
MinWidth="150">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding PresetName, UpdateSourceTrigger=Explicit}" VerticalAlignment="Center" Height="20" BorderThickness="0" LostFocus="TextBox_LostFocus" KeyUp="TextBox_KeyUp"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The first Item of the combobox is a default preset with a corresponding default name in the textbox. The user therefore shouldn't be able to make input to this first item - thus I want to disable the textbox of the first item.
I know I could just run a function in the constructor of the containing class or the viewmodel, which disables the textbox on the first index, however I'm wondering if this is possible directly within the xaml code (which I would find a more elegant way of doing such static things).
You could make use of the fact that the PreviousData RelativeSource will return null
for the first element of a collection. Knowing that you can add a DataTrigger to your DataTemplate to set the IsEnabled
property of the TextBox
to false.
Here is a simplified version of the ItemTemplate
with a PreviousData
binding:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBox x:Name="TextBox" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=PreviousData}}"
Value="{x:Null}">
<Setter TargetName="TextBox" Property="IsEnabled" Value="False" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ComboBox.ItemTemplate>