-1

I'm designed a Contact Box in XAML

<DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox Grid.Column="0" SelectedItem="{Binding Type, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
            <ComboBoxItem Content="1">Mobile</ComboBoxItem>
            <ComboBoxItem Content="2">Phone</ComboBoxItem>
        </ComboBox>
        <TextBox Text="{Binding Contact, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
    </Grid>
</DataTemplate>

The Properties are

public int Type { get; set; }
public string Contact { get; set; }

Initial Value of Type is ZERO (i.e., Type = 0;).

Conditions to Implement:

  1. If Type is equal to 1 or 2, then I need to enable the TextBox - IsEnabled = True
  2. If Type is 1, then the TextBox.MaxLength should be 10
  3. If Type is 2, then the TextBox.MaxLength should be 11

I tried the following piece of Code:

<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding Path=Type}" Value="0">
        <Setter Property="TextBox.IsEnabled" Value="False" />
    </DataTrigger>

    <DataTrigger Binding="{Binding Path=Type}" Value="1">
        <Setter Property="TextBox.MaxLength" Value="10" />
    </DataTrigger>

    <DataTrigger Binding="{Binding Path=Type}" Value="2">
        <Setter Property="TextBox.MaxLength" Value="11" />
    </DataTrigger>
</DataTemplate.Triggers>

But the above code is not working. Kindly assist me how to achieve the logic in DataTrigger within the DataTemplate.

B.Balamanigandan
  • 4,713
  • 11
  • 68
  • 130

1 Answers1

1

Your TextBox could have a Style with DataTriggers:

<TextBox Text="{Binding Contact, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.Style>
        <Style TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Type}" Value="0">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Type}" Value="1">
                    <Setter Property="MaxLength" Value="10" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Type}" Value="2">
                    <Setter Property="MaxLength" Value="11" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

If the Type property is suposed to change its value after the DataTemplate is instantiated, the owning class needs to implements the INotifyPropertyChanged interface.

Clemens
  • 123,504
  • 12
  • 155
  • 268