2012-01-23 9 views

答えて

3

のは、あなたがTextBoxButtonを持っている、とあなたはButtonときを無効にしたいとしましょうTextBox空です。これは、簡単にDataTriggersで達成することができます:

<TextBox x:Name="textBox" /> 
<Button> 
    <Button.Style> 
     <Style> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding Text, ElementName=textBox}" Value=""> 
        <Setter Property="Button.IsEnabled" Value="False" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </Button.Style> 
</Button> 
+0

あなたのソリューションは最高です!タイ! –

0

のサンプルコードを掲示することは参考になるとはるかに優れたソリューションを可能にするが、私はまだdata bindingをお勧めすることができます。あなたのコントロールのリソースセクションが

<local:ButtonVisibilityConverter Name="ButtonVisibilityConverter"/> 

が含まれており、地元で参照される名前空間内のクラスButtonVisibilityConverterを定義した

<Button Name="btnFoo" 
     Enabled="{Binding ElementName=txtblkBar, Converter={StaticResource ButtonVisibilityConverter}"/> 

ような何か。上記にリンクされたページのデータ変換セクションには、コンバータクラスの例があります。

EDIT:txtblkBarが空の時はいつでも無効にボタンを設定し

コード:

[ValueConversion(typeof(TextBlock), typeof(bool?))] 
public class ButtonVisibilityConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     TextBlock txtblk = value as TextBlock; 
     if (null == txtblk) 
      return false; 
     return !string.IsNullOrEmpty(txtblk.Text); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     // Don't need to use the back conversion 
     throw new NotImplementedException(); 
    } 
} 
+0

グレートを実行するために想定されていない場合、それは自動的にボタンを無効にするの世話をします!!!! ButtonVisibilityConverterを実装する方法について、より多くのコードを記述できますか? –

+0

[String.IsNullOrEmptyメソッド](http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx)をお勧めします。 'return!String.IsNullOrEmpty(txtblk.Text); ' – LPL

+0

@LPL正しくは、 –

4

私はこれはテキストボックスが検証エラーを持っているかどう基づくボタンでEnabledプロパティをトリガーについてyour other questionに関連していると仮定しています。

はそれがそうなら、あなたはそれがすべてのエラーを持っているかどうかを確認するためにTextBox.Validation.HasErrorプロパティをテストするためにDataTriggerを使用して、そのボタンを無効にした場合

<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}"> 
    <Setter Property="IsEnabled" Value="True" /> 
    <DataTrigger Binding="{Binding ElementName=MyTextBox, Path=Validation.HasError" Value="True"> 
     <Setter Property="IsEnabled" Value="False"/> 
    </DataTrigger> 
</Style> 

は、あなたがこのためにValidatesOnDataErrors="True"であなたのTextBoxをバインドしていることを確認してください仕事

<TextBox x:Name="MyTextBox" Text="{Binding SomeText, ValidatesOnDataErrors=True }" /> 

あなたの他の質問に対する私のコメントはここでも適用されます。私は個人的にあなたのViewModelIDataErrorInfoを実装し、SaveCommand.CanExecute()だけViewModel.IsValid場合はtrueを返すになるだろう。 SaveCommand

+0

あなたのご意見をいただきありがとうございます。 –

関連する問題