I'm writing a WPF program, and it involves someone typing in a number, and enabling a corresponding number of text boxes. Currently I have a system that checks every single text box such as
private void navnumbox_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
if (Int32.Parse(navnumbox.Text) > 0)
{
One.IsEnabled = true;
}
if (Int32.Parse(navnumbox.Text) > 1)
{
Two.IsEnabled = true;
}
}
}
I want to put this into a loop, and I'm think that I may need to store One and Two in an array, but I have tried but I don't know how to access them
Maybe you could try something like this (I wasn't able to test it sorry).
private void navnumbox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBoxesMap = new Dictionary<int,TextBox>()
{
{1, One},
{2, Two}
// etc
};
try
{
int number = int.Parse(navnumbox.Text)
foreach(var item in textBoxesMap)
{
if(item.Key <= number)
{
item.Value.IsEnabled = true;
}
}
}
}
And you can obviously place the map somewhere else. An alternative (and better) approach to this would be to use XAML - there is another answer on this question that demonstrates how to do so.
I think the better approach is to use Converter for Visibility property of the TextBoxes One and Two by ElementBinding to the navnumbox Path=Text.
I your case you will need separate converters for TextBox.Enable for TextBoxes One and Two.
Here XAML for the Window:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication2="clr-namespace:WpfApplication2"
Title="MainWindow"
Height="350"
Width="525">
<Window.Resources>
<wpfApplication2:MyConverter x:Key="MyConverter"></wpfApplication2:MyConverter>
</Window.Resources>
<Grid>
<StackPanel>
<TextBox x:Name="MyText"></TextBox>
<TextBox IsEnabled="{Binding ElementName=MyText, Path=Text, Converter={StaticResource MyConverter}}"></TextBox>
</StackPanel>
</Grid>
</Window>
Here implementation of the Converter for TexBox "One"
public class MyConverter
: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string myValue = value as string;
int result = 0;
if (myValue != null)
{
int.TryParse(myValue,out result);
}
return result > 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// not relevant for your application
throw new NotImplementedException();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.