Search code examples
c#wpfxamldatatrigger

WPF XAML - Design time and visibility of textbox


I use Visual Studio 2019 with WPF / MVVM.

I have set a trigger to a textbox to control its visibiliy. And during runtime this works well, the trigger checks the state of a radiobutton and sets the visibiliy of the textbox accoring to the radiobutton's state.

But during designtime this textbox is not visible. How could I make this textbox to be visible during designtime ?

This is the XAML I have for the trigger:

<Style x:Key="text" TargetType="TextBox">

    <Style.Triggers>

       <DataTrigger Binding="{Binding ElementName=Radiobutton1, Path=IsChecked}" Value="true">
            <Setter Property="Visibility" Value="Visible"/>
        </DataTrigger>

        <DataTrigger Binding="{Binding ElementName=Radiobutton1, Path=IsChecked}" Value="false">
            <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>

    </Style.Triggers>
</Style>


<TextBox Style="{StaticResource text}"  Text="test..... />

I found this article https://social.msdn.microsoft.com/Forums/en-US/cacc5c30-8aa0-43c5-ad07-b063028653a2/designmode-and-visibility?forum=wpf and did some tests using "DesignerProperties.IsInDesignMode" but I can not make this run,I get errors like "datatrigger can not be added to setterbasecollection".

Also I don't know if "DesignerProperties.IsInDesignMode" is the right approach...


Solution

  • This is a workaround:

    <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=Radiobutton1, Path=IsChecked}" Value="true">
                <Setter Property="Visibility" Value="Visible"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=Radiobutton1, Path=IsChecked}" Value="false">
                <Setter Property="Visibility" Value="Collapsed"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding Designtime}" Value="true">
                <Setter Property="Visibility" Value="Visible"/>
            </DataTrigger>
    

    then in Viewmodel:

    public bool Designtime { get; set; }
    
    public ViewModel()
    {
        if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
        {
            Designtime = true;
        }
    }
    

    And in the Window Tag

    d:DataContext="{d:DesignInstance {x:Type local:ViewModel},IsDesignTimeCreatable=True}"