如何创建将外部XAML排除在外的“包装器”视图?

在WPF项目中,我正在创建一个包含许多步骤的向导。每个步骤都有自己的看法。当前,每个视图都具有相同的外部XAML元素,例如,步骤的标题为TextBlock,但其下的内容不同。

例如,一个典型的视图如下所示:

STEP X VIEW

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Text="Step X text goes here"/>
    <Grid Grid.Row="1">
        <!-- CONTENT OF STEP X GOES HERE -->
    </Grid>     
</Grid>

我想做的是能够“分解”每个步骤的公共外部XAML到另一个视图,并将每个步骤的内容作为该新分解视图的内容放置。这样,我可以避免重复相同的外部XAML,并且如果我决定更改每个步骤标题的实现,则只需要在一个地方进行即可。

我确定ContentPresenter是解决方案的一部分。因此,类似:

WRAPPERVIEW:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Text="Step X text goes here"/>
    <Grid Grid.Row="1">
        <ContentPresenter Content="Content of Step X ??????"/>
    </Grid>
</Grid>

我的问题是:

1)我对WrapperView的实现是否正确?

2)ContentPresenterWrapperView内容属性的绑定是什么?

3)如何使用Text为每一步自定义TextBlock的{​​{1}}?

4)如何使用WrapperView来使客户端XAML看起来像任何步骤视图的XAML。

因此,将WrapperView用于StepXView

新的STEP X VIEW

WrapperView
ppsda 回答:如何创建将外部XAML排除在外的“包装器”视图?

您对使用ContentPresenter有很好的直觉。对我来说,看起来就像您需要一个HeaderedContentControl,这是一个可处理ControlHeader属性的可模板化Content

尽管您可以直接使用HeaderedContentControl,但如果您以后要对其进行进一步的自定义,我发现可以更清晰地继承它:

public class WrapperView : HeaderedContentControl { }

在XAML中,您可以对其进行模板化并随意使用:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp1">
    <Window.Resources>
        <Style TargetType="{x:Type local:WrapperView}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="local:WrapperView">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>
                            <ContentPresenter HorizontalAlignment="Center" Grid.Row="0" Content="{TemplateBinding Header}"/>
                            <Grid Grid.Row="1" HorizontalAlignment="Center">
                                <ContentPresenter Content="{TemplateBinding Content}"/>
                            </Grid>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <local:WrapperView Header ="Step X Title Text">
            <Rectangle Width="50" Height="50" Fill="Blue"/>
        </local:WrapperView>
    </Grid>
</Window>

此处的关键是使用TemlateBinding来回答您的第二个问题。

要使其更加整洁,您可以将此Style移离Window.Resources,并在Themes\Generics.xaml中进行设置,以使Style成为默认设置。

本文链接:https://www.f2er.com/3103994.html

大家都在问