I have a Button and a TextBox in my WPF app. How can I make the Button not enabled until the user enters some text in the TextBox?
问题:
回答1:
This should do it:
<StackPanel>
<TextBox x:Name="TheTextBox" />
<Button Content="Click Me">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True" />
<Style.Triggers>
<DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</StackPanel>
回答2:
In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text
that is bound to your TextBox and you would have a ICommand property Apply
(or similar) that is bound to the button:
<Button Command="Apply">Apply</Button>
The ICommand
interface has a Method CanExecute
that is where you return true
if (!string.IsNullOrWhiteSpace(this.Text)
. The rest is done by WPF for you (enabling/disabling, executing the actual command on click).
The linked article explains it in detail.
回答3:
By code:
btn_edit.IsEnabled = true;
By XAML:
<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />
回答4:
I know this isn't as elegant as the other posts, but it's a more straightforward xaml/codebehind example of how to accomplish the same thing.
Xaml:
<StackPanel Orientation="Horizontal">
<TextBox Name="TextBox01" VerticalAlignment="Top" HorizontalAlignment="Left" Width="70" />
<Button Name="Button01" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,0" />
</StackPanel>
CodeBehind:
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Button01.IsEnabled = False
Button01.Content = "I am Disabled"
End Sub
Private Sub TextBox01_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox01.TextChanged
If TextBox01.Text.Trim.Length > 0 Then
Button01.IsEnabled = True
Button01.Content = "I am Enabled"
Else
Button01.IsEnabled = False
Button01.Content = "I am Disabled"
End If
End Sub
回答5:
You could subscribe to the TextChanged
event on the TextBox
and if the text is empty set the Button
to disabled. Or you could bind the Button.IsEnabled
property to the TextBox.Text
property and use a converter that returns true if there is any text and false otherwise.