WPF 显示/隐藏带有触发器的控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17718623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Showing / Hiding a control with triggers
提问by user1683456
I'm new to WPF and I trying to create xaml logic to show / hide a control based on the value of the AllowMiscTitle on the ViewModel. The xaml consist of two fields a combobox of the standard tiles ("Mr", "Mrs", ..., "Other") when "Other" is selected I want the textbox to display.
我是 WPF 的新手,我尝试创建 xaml 逻辑以根据 ViewModel 上 AllowMiscTitle 的值显示/隐藏控件。The xaml consist of two fields a combobox of the standard tiles ("Mr", "Mrs", ..., "Other") when "Other" is selected I want the textbox to display.
I've created the follow xaml:
我创建了以下 xaml:
<DockPanel Validation.Error="Validation_Error" HorizontalAlignment="Stretch">
<ComboBox ItemsSource="{Binding Path=Titles, Mode=OneTime}"
Text="{Binding Path=Title}"/>
<TextBox x:Name="TxtBxTitle" Margin="5,5" Visibility="Visible">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=AllowMiscTitle}" Value="false">
<Setter Property="TextBox.Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</DockPanel>
回答by Kapitán Mlíko
That Triggerwon't work because you have set Visibilityproperty explicitly in TextBox
这Trigger行不通,因为您已Visibility在TextBox
Do it like this:
像这样做:
<TextBox x:Name="TxtBxTitle" Margin="5,5">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=AllowMiscTitle}" Value="false">
<Setter Property="TextBox.Visibility" Value="Hidden"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
The reason for this is Dependency property value precedence.
这样做的原因是Dependency 属性值优先级。
回答by Nitesh
There is a
有一个
<BooleanToVisibilityConverter x:Key="BoolToVis"></BooleanToVisibilityConverter>
You can use it as following
您可以按以下方式使用它
<TextBox Visibility="{Binding YourPropertyName, Converter={StaticResource BoolToVis}}"></TextBox>
回答by Vishal
If I got your question right:-
如果我问对了你的问题:-
If your selected value is binded to some property in the ViewModel like:-
如果您选择的值绑定到 ViewModel 中的某些属性,例如:-
private string _GenderType;
public string GenderType
{
get
{
return _GenderType;
}
set
{
_GenderType= value;
RaisePropertyChanged("GenderType");
In xaml:-
在 xaml 中:-
<TextBox.Style>
<Style>
<Setter Property="TextBox.Visibility" value="Hidden"/>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=GenderType,ElementName=Combo1}" Value="Other">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>

