SSW
SSW

Reputation: 1

How to set max length validation on textbox using combobox selection

In my project used 1 ComboBox and 1 textbox, in ComboBox multi byte length available like 8,12,15,20,25,30 etc.

If user select ComboBox 12Byte at the same time in text box user allow only 12byte in text box and after change 20 byte so user allow 20 byte data in text box at run time.

How to set max length validation on textbox using Combobox selection.

Upvotes: 0

Views: 321

Answers (1)

Demetrius Axenowski
Demetrius Axenowski

Reputation: 761

How about something like this?


        <ComboBox x:Name="LengthComboBox" ItemsSource="{Binding Lengths}" VerticalAlignment="Top"/>
        <TextBox MaxLength="{Binding ElementName=LengthComboBox, Path=SelectedValue}" VerticalAlignment="Top"/>

Lengths items should be of type int

This is direct Binding. If you need some calulation, you have to use Converter

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <local:MyConverter x:Key="MyConverter"/>
    </Window.Resources>
    <Grid>
        <StackPanel Orientation="Vertical">
        <ComboBox x:Name="LengthComboBox" ItemsSource="{Binding Lengths}" VerticalAlignment="Top"/>
            <TextBox MaxLength="{Binding ElementName=LengthComboBox, Path=SelectedValue, Converter={StaticResource MyConverter}}" VerticalAlignment="Top"/>
        </StackPanel>
    </Grid>
</Window>

---------------

public class MyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is not int)
                return value;

            return (int)value * 2;
        }

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

PS: Lengths is a Property of the ViewModel behind the View

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new VM()
            {
                Lengths = new List<int>()
                {
                    1, 2, 5, 9, 15, 30
                }
            };
        }

Upvotes: 1

Related Questions