2011-05-22 16 views
1

在WPF中,我想要TextBox和Button。僅當TextBox中的文本長度爲10時才應啓用按鈕。在有效文本框上啓用按鈕

我正在嘗試使用綁定來完成此操作,但它不會觸發IsValid屬性讀取,因爲我在TextBox中鍵入內容。

這怎麼辦?

回答

2

如果你只是這種依賴和一個值,它是有效的,你可以使用樣式:

<TextBox Name="tbTest"/> 
<Button Content="Do Stuff"> 
    <Button.Style> 
     <Style TargetType="{x:Type Button}"> 
      <Setter Property="IsEnabled" Value="False"/> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding ElementName=tbTest, Path=Text.Length}" Value="10"> 
        <Setter Property="IsEnabled" Value="true"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </Button.Style> 
</Button> 

否則,您應該定義一個ValidationRule應將其添加到文本綁定中。然後,您可以使用代碼隱藏來檢查它是否有效,或將IsEnabled屬性綁定到Validation.HasError(使用ValueConverter反轉布爾值)。

0

這不是個好主意,但它是有用的:你可以用框TextChanged

private void textBox1_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     if (textBox1.Text.Length == 10) 
      button1.IsEnabled = true; 
     else 
      button1.IsEnabled = false; 
    } 
+0

這是觸發對。 – dave 2011-05-22 14:30:11

2

你有很多方法可以做到這一點。

例如,你可以使用綁定轉換器:

<TextBox> 
    <Binding Path="Text" UpdateSourceTrigger="PropertyChanged"> 
     <Binding.ValidationRules> 
      <WpfApplication1:MyValidationRule /> 
     </Binding.ValidationRules> 
    </Binding> 
</TextBox> 

<Button> 
    <Button.IsEnabled> 
     <Binding ElementName="TB" Path="(Validation.HasError)"> 
      <Binding.Converter> 
       <WpfApplication1:TrueToFalseConverter/> 
      </Binding.Converter> 
     </Binding> 
    </Button.IsEnabled> 
</Button> 

public class TrueToFalseConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return !(bool) value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return !(bool)value; 
    } 
} 

public class MyValidationRule : ValidationRule 
{ 
    public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
    { 
     return new ValidationResult((value as string).Length == 10, null); 
    } 
} 

或(我會推薦它),你可以使用命令和CanExecute

<Button Command="{Binding Path=MyCommand}" /> 
<TextBox Text="{Binding Path=Text, UpdateSourceTrigger=PropertyChanged}" /> 

public class MainWindowViewModel 
{ 
    public RelayCommand MyCommand { get; private set; } 

    public string Text { get; set; } 

    public MainWindowViewModel() 
    { 
     Text = ""; 
     MyCommand = new RelayCommand(MyAction, CanExecute); 
    } 

    private bool CanExecute(object x) 
    { 
     return Text.Length == 10; 
    } 

    .... 
} 
相關問題