WPF Showing / Hiding a control with triggers

人盡茶涼 提交于 2020-02-01 04:58:20

问题


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.

I've created the follow 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>

回答1:


That Trigger won't work because you have set Visibility property explicitly in 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.




回答2:


There is a

<BooleanToVisibilityConverter x:Key="BoolToVis"></BooleanToVisibilityConverter>

You can use it as following

<TextBox Visibility="{Binding YourPropertyName, Converter={StaticResource BoolToVis}}"></TextBox>



回答3:


If I got your question right:-

If your selected value is binded to some property in the ViewModel like:-

private string _GenderType;

        public string GenderType
        {
            get
            {
                return _GenderType;
            }
            set
            {
                _GenderType= value;
 RaisePropertyChanged("GenderType");

In 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>


来源:https://stackoverflow.com/questions/17718623/wpf-showing-hiding-a-control-with-triggers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!