Home > OS >  Different templates of one UserControl WPF
Different templates of one UserControl WPF

Time:06-15

Does someone have an idea how I could handle this case?

I have UserControl where I am able to put text in one column and photo in second column. But I need to be able to change the order of those two. Actually I need three states:

  • Textbox on the left / Image on the right
  • Image on the left / Textbox on the right
  • Full width textbox

I would like to be able to choose one option from combobox. Here is a design example: Example

This UserControl is also a ItemTemplate in another UserControl so when I add object of type of this usercontrol it will be added to view also. What is the best way to do it?

CodePudding user response:

since it is in a datatemplate anyway

    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <TextBox x:Name="TextElement" Grid.Column="0" Grid.ColumnSpan="1"/>
            <Image x:Name="ImageElement" Grid.Column="1"/>
        </Grid>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding SelectedLayout}" Value="{x:Static vm:Layout.ImageText}">
                <Setter TargetName="TextElement" Property="Grid.Column" Value="1"/>
                <Setter TargetName="ImageElement" Property="Grid.Column" Value="0"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding SelectedLayout}" Value="{x:Static vm:Layout.TextOnly}">
                <Setter TargetName="TextElement" Property="Grid.ColumnSpan" Value="2"/>
                <Setter TargetName="ImageElement" Property="Visibility" Value="Collapsed"/>
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>

Or as UserControl

    <UserControl x:Name="userControl" ...>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <TextBox Grid.Column="{Binding SelectedLayout, ElementName=userControl, Converter={StaticResource LayoutToColumnConverter}}"
                     Grid.ColumnSpan="{Binding SelectedLayout, ElementName=userControl, Converter={StaticResource LayoutToColumnSpanConverter}}"/>
            <Image Grid.Column="{Binding SelectedLayout, ElementName=userControl, Converter={StaticResource LayoutToColumnConverter}, ConverterParameter=invertedOrWhatever}"/>
        </Grid>
    </UserControl>



    <whatever:MyUserControl SelectedLayout="{Binding SelectedLayout, ElementName=LayoutCombobox}"/>
  • Related