简体   繁体   English

如何使用 combobox 选择在文本框上设置最大长度验证

[英]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.在我的项目中,使用了 1 个 ComboBox 和 1 个文本框,在 ComboBox 中,多字节长度可用,如 8、12、15、20、25、30 等。

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.如果用户 select ComboBox 12 字节同时在文本框中用户只允许 12 字节在文本框中,更改后 20 字节因此用户在运行时允许文本框中有 20 字节数据。

How to set max length validation on textbox using Combobox selection.如何使用 Combobox 选择设置文本框的最大长度验证。

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 Lengths项应为int类型

This is direct Binding .这就是直接Binding If you need some calulation, you have to use Converter如果你需要一些计算,你必须使用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 PS: LengthsView后面ViewModel的一个属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM