简体   繁体   中英

disable/enable a button depending on textbox in xaml

I have a TextBox

<TextBox x:Name="searchTextBox" Width="200" Height="30" HorizontalAlignment="Left"/>

and two Buttons

<Button x:Name="previous" Style="{StaticResource AppBarButtonStyle}" Tapped="OnOptionItemTapped" IsEnabled="False">
    <Image Source="/Assets/images/left_arrow.png"/>
</Button>
    <Button x:Name="next" Style="{StaticResource AppBarButtonStyle}"  Tapped="OnOptionItemTapped" IsEnabled="False">
    <Image Source="/Assets/images/right_arrow.png"/>
</Button>

Is there a simple solution to enable/disable the Buttons trough the TextBox?

Like for example if the TextBox is empty the Buttons are disabled. And if the TextBox is not empty the Buttons are enabled.

You could apply a text changed event that checks the input every time it changes.

<TextBox x:Name="searchTextBox" Width="200" Height="30" HorizontalAlignment="Left" TextChanged="TextBox_TextChanged" />

If the text is the way you need it, you can turn the button enabled/disabled.

public void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (searchTextBox.Text == result)
        next.IsEnabled = false;
}

EDIT: Other than code behind like this approach you could learn about the MVVM design pattern. The other answers partly used practices common in MVVM .

There are various good tutorials for this all around the web.

How about using binding + converter? I guess this concept is valid for UWP as well.

Eg you have a view model with property SearchText which is bound to the text in the TextBox. Then you can do the following:

<Window.Resources>
    <local:StringToBoolConverter x:Key="StringToBoolConverter" />
</Window.Resources>

...

<TextBox x:Name="searchTextBox" Width="200" Height="30" HorizontalAlignment="Left" Text="{Binding SearchText}"/>
<Button x:Name="previous" IsEnabled="{Binding SearchText, Converter={StaticResource StringToBoolConverter}}"/>

And the converter code would be quite simple:

public class StringToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !string.IsNullOrEmpty(value?.ToString());
    }

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

Another way to go is using Command pattern for the buttons. The ICommand interface has CanExecute method that will cantually disable or enable your buttons depending on the return value. See examples in the internet or here .

Use binding for IsEnabled.

<Button x:Name="previous" Style="{StaticResource AppBarButtonStyle}" 
 Tapped="OnOptionItemTapped" IsEnabled="{Binding ElementName=searchTextBox, 
Path=Text.Length, Mode=OneWay}"></Button>

You can also use Data Triggers but the above is simplest. Converters are not required.

I use converters in Xamarin Forms (XAML) to achieve this, which should be the same/similar for your scenario. Usually a combination of IsEnabled and Opacity because I like to make more transparent a disabled button.

For example you can create two converters that will interpret a string (the text in the entry field).

The first converter will determine whether the text is empty or not, returning true when there is text.

public class StringToBoolConverter
    : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !string.IsNullOrEmpty(value?.ToString());
    }

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

The second converter will determine the opacity level, returning 100% (eg: 1.0 ) when there is text, and 0.3 when the field is empty.

public class StringToFloatConverter
    : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !string.IsNullOrEmpty(value?.ToString())? 1.0 : 0.3;
    }

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

Now I tag both converters with a more meaningful name in App.xaml as follows:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:converters="clr-namespace:Sasw.EasyQr.Converters;assembly=Sasw.EasyQr"
             mc:Ignorable="d"
             x:Class="Sasw.EasyQr.App">
    <Application.Resources>
        <ResourceDictionary>
            <converters:StringToBoolConverter x:Key="EnabledWhenFilledConverter"></converters:StringToBoolConverter>
            <converters:StringToFloatConverter x:Key="OpaqueWhenFilledConverter"></converters:StringToFloatConverter>
        </ResourceDictionary>
    </Application.Resources>
</Application>

and now I can refer to these converters from any button control, for example:

<Entry
    Text = "{Binding Text}"
    Placeholder="{x:Static resources:AppResources.PlaceholderEnterText}"
    HorizontalOptions="FillAndExpand"
    VerticalTextAlignment="Center"
    VerticalOptions="End"></Entry>
<ImageButton 
    Command="{Binding TapClear}"
    IsEnabled="{Binding Text, Converter={StaticResource EnabledWhenFilledConverter}}"
    Source ="backspace.png" 
    WidthRequest="30"
    Opacity="{Binding Text, Converter={StaticResource OpaqueWhenFilledConverter}}"
    BackgroundColor="Transparent"
    HorizontalOptions="End"
    VerticalOptions="CenterAndExpand"></ImageButton>

and see how the button is automatically enabled and made opaque as soon as text is entered in the Entry, and disabled and made transparent when text is deleted.

按钮透明和禁用

按钮已启用且不透明

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.

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