2014-10-29 91 views
4

正如標題所示,Iam試圖在WPF中顯示/隱藏TextBox而無需在MainWindow.xaml.cs文件中編寫代碼。複選框顯示/隱藏文本框WPF

型號:

public class Person 
{ 
    public string Comment { get; set; } 
} 

查看:

<Window x:Class="PiedPiper.View.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    x:Name="Window" 
    Title="WPF" Height="400" Width="400"> 

    <CheckBox Content="Show comment" Name="CommentCheckBox"/> 
    <TextBox Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" Visibility="Hidden" Name="CommentTextBox"></TextBox> 
</Grid> 

視圖模型:

public class PersonViewModel : INotifyPropertyChanged 
    { 
    public PersonViewModel(Person person) 
    { 
     Comment = person.Comment; 
    } 

    private string _comment; 
    public string Comment 
    { 
     get { return _comment; } 
     set { _comment = value; OnPropertyChanged("Comment"); } 
    } 

    private void OnPropertyChanged(string propertyName) 
    { 
     var handler = PropertyChanged; 

     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
} 

所以在TextBox應在開始時被隱藏,但可見當複選框被選中。請幫忙!

謝謝。

+0

我想你會希望首先將CheckBox綁定到視圖模型上的屬性,然後創建一個Converter將你的布爾屬性值轉換爲可見性枚舉。 – 2014-10-29 10:45:07

回答

8

您可以將TextBox.Visiblity綁定到CheckBox.IsChecked。如果你想切換HiddenVisible然後之間,你需要或者編寫自定義IValueConverter或創建簡單Style.Trigger

<StackPanel> 
    <CheckBox Content="Show comment" Name="CommentCheckBox"/> 
    <TextBox Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" Name="CommentTextBox"> 
     <TextBox.Style> 
      <Style TargetType="{x:Type TextBox}"> 
       <Setter Property="Visibility" Value="Hidden"/> 
       <Style.Triggers> 
        <DataTrigger Binding="{Binding ElementName=CommentCheckBox, Path=IsChecked}" Value="True"> 
         <Setter Property="Visibility" Value="Visible"/> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </TextBox.Style> 
    </TextBox> 
</StackPanel> 

,如果你想CollapsedVisible之間切換,還有一個更簡單的方法,你可以用建立在BooleanToVisibilityConverter

<StackPanel> 
    <StackPanel.Resources> 
     <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/> 
    </StackPanel.Resources> 
    <CheckBox Content="Show comment" Name="CommentCheckBox"/> 
    <TextBox 
     Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" 
     Visibility="{Binding ElementName=CommentCheckBox, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}" 
     Name="CommentTextBox"/> 
</StackPanel>