Xamarin.Forms ContentView

Download Sample 샘플 다운로드

클래스는 Xamarin.FormsContentView 단일 자식 요소를 포함하는 형식 Layout 이며 일반적으로 재사용 가능한 사용자 지정 컨트롤을 만드는 데 사용됩니다. 클래스는 ContentView .에서 TemplatedView상속됩니다. 이 문서 및 관련 샘플에서는 클래스를 기반으로 ContentView 사용자 지정 CardView 컨트롤을 만드는 방법을 설명합니다.

다음 스크린샷은 클래스에서 파생되는 컨트롤을 ContentView 보여줍니다CardView.

CardView sample application screenshot

클래스는 ContentView 단일 속성을 정의합니다.

  • ContentView 개체입니다. 이 속성은 데이터 바인딩의 대상이 될 수 있도록 개체에 의해 BindableProperty 지원됩니다.

ContentView 또한 클래스에서 TemplatedView 속성을 상속합니다.

  • ControlTemplateControlTemplate 컨트롤의 모양을 정의하거나 재정의할 수 있는 값입니다.

속성에 ControlTemplate 대한 자세한 내용은 ControlTemplate을 사용하여 모양 사용자 지정을 참조 하세요.

사용자 지정 컨트롤 만들기

클래스는 ContentView 그 자체로 기능이 거의 없지만 사용자 지정 컨트롤을 만드는 데 사용할 수 있습니다. 샘플 프로젝트는 카드 모양 레이아웃에 이미지, 제목 및 설명을 표시하는 UI 요소인 컨트롤을 정의 CardView 합니다.

사용자 지정 컨트롤을 만드는 프로세스는 다음과 같습니다.

  1. Visual Studio 2019에서 템플릿을 ContentView 사용하여 새 클래스를 만듭니다.
  2. 새 사용자 지정 컨트롤에 대한 코드 숨김 파일에서 고유한 속성 또는 이벤트를 정의합니다.
  3. 사용자 지정 컨트롤에 대한 UI를 만듭니다.

참고 항목

XAML 대신 코드에서 레이아웃이 정의된 사용자 지정 컨트롤을 만들 수 있습니다. 간단히 하기 위해 샘플 애플리케이션은 XAML 레이아웃을 사용하여 단일 CardView 클래스만 정의합니다. 그러나 샘플 애플리케이션에는 코드에서 사용자 지정 컨트롤을 사용하는 프로세스를 보여 주는 CardViewCodePage 클래스가 포함되어 있습니다.

코드 숨김 속성 만들기

사용자 지정 컨트롤은 CardView 다음 속성을 정의합니다.

  • CardTitlestring: 카드 표시되는 제목을 나타내는 개체입니다.
  • CardDescriptionstring: 카드 표시되는 설명을 나타내는 개체입니다.
  • IconImageSourceImageSource: 카드 표시된 이미지를 나타내는 개체입니다.
  • IconBackgroundColorColor: 카드 표시된 이미지의 배경색을 나타내는 개체입니다.
  • BorderColorColor: 카드 테두리, 이미지 테두리 및 구분선의 색을 나타내는 개체입니다.
  • CardColorColor: 카드 배경색을 나타내는 개체입니다.

참고 항목

이 속성은 BorderColor 데모를 위해 여러 항목에 영향을 줍니다. 필요한 경우 이 속성을 세 가지 속성으로 나눌 수 있습니다.

각 속성은 인스턴스에서 BindableProperty 지원됩니다. 백업 BindableProperty 을 사용하면 MVVM 패턴을 사용하여 각 속성의 스타일을 지정하고 바인딩할 수 있습니다.

다음 예제에서는 백업 BindableProperty을 만드는 방법을 보여줍니다.

public static readonly BindableProperty CardTitleProperty = BindableProperty.Create(
    "CardTitle",        // the name of the bindable property
    typeof(string),     // the bindable property type
    typeof(CardView),   // the parent object type
    string.Empty);      // the default value for the property

사용자 지정 속성은 및 SetValue 메서드를 사용하여 GetValue 개체 값을 가져와서 설정합니다BindableProperty.

public string CardTitle
{
    get => (string)GetValue(CardView.CardTitleProperty);
    set => SetValue(CardView.CardTitleProperty, value);
}

개체에 대한 BindableProperty 자세한 내용은 바인딩 가능한 속성을 참조 하세요.

UI 정의

사용자 지정 컨트롤 UI는 ContentView 컨트롤의 루트 요소 CardView 로 사용합니다. 다음 예제에서는 XAML을 CardView 보여줍니다.

<ContentView ...
             x:Name="this"
             x:Class="CardViewDemo.Controls.CardView">
    <Frame BindingContext="{x:Reference this}"
            BackgroundColor="{Binding CardColor}"
            BorderColor="{Binding BorderColor}"
            ...>
        <Grid>
            ...
            <Frame BorderColor="{Binding BorderColor, FallbackValue='Black'}"
                   BackgroundColor="{Binding IconBackgroundColor, FallbackValue='Grey'}"
                   ...>
                <Image Source="{Binding IconImageSource}"
                       .. />
            </Frame>
            <Label Text="{Binding CardTitle, FallbackValue='Card Title'}"
                   ... />
            <BoxView BackgroundColor="{Binding BorderColor, FallbackValue='Black'}"
                     ... />
            <Label Text="{Binding CardDescription, FallbackValue='Card description text.'}"
                   ... />
        </Grid>
    </Frame>
</ContentView>

요소는 ContentView 인스턴스에 x:Name바인딩된 개체에 액세스하는 데 사용할 수 있는 속성을 이 속성으로 CardView 설정합니다. 레이아웃의 요소는 바인딩된 개체에 정의된 값에 대한 속성의 바인딩을 설정합니다.

데이터 바인딩에 대한 자세한 내용은 Xamarin.Forms 데이터 바인딩을 참조하세요.

참고 항목

이 속성은 FallbackValue 바인딩 null이 .인 경우 기본값을 제공합니다. 또한 Visual Studio의 XAML 미리 보기 에서 컨트롤을 렌더링할 수 있습니다 CardView .

사용자 지정 컨트롤 인스턴스화

사용자 지정 컨트롤 네임스페이스에 대한 참조를 사용자 지정 컨트롤을 인스턴스화하는 페이지에 추가해야 합니다. 다음 예제에서는 XAML의 인스턴스에 추가된 컨트롤이라는 네임스페이스 참조를 ContentPage 보여 줍니다.

<ContentPage ...
             xmlns:controls="clr-namespace:CardViewDemo.Controls" >

참조가 추가 CardView 되면 XAML에서 인스턴스화할 수 있으며 해당 속성이 정의됩니다.

<controls:CardView BorderColor="DarkGray"
                   CardTitle="Slavko Vlasic"
                   CardDescription="Lorem ipsum dolor sit..."
                   IconBackgroundColor="SlateGray"
                   IconImageSource="user.png"/>

코드에서 A CardView 를 인스턴스화할 수도 있습니다.

CardView card = new CardView
{
    BorderColor = Color.DarkGray,
    CardTitle = "Slavko Vlasic",
    CardDescription = "Lorem ipsum dolor sit...",
    IconBackgroundColor = Color.SlateGray,
    IconImageSource = ImageSource.FromFile("user.png")
};

ControlTemplate을 사용하여 모양 사용자 지정

클래스에서 ContentView 파생되는 사용자 지정 컨트롤은 XAML, 코드를 사용하여 모양을 정의하거나 모양을 전혀 정의하지 않을 수 있습니다. 모양을 정의하는 ControlTemplate 방법에 관계없이 개체는 사용자 지정 레이아웃으로 모양을 재정의할 수 있습니다.

레이아웃이 CardView 일부 사용 사례에 비해 너무 많은 공간을 차지할 수 있습니다. A는 ControlTemplate 압축된 목록에 적합한 보다 컴팩트한 보기를 제공하도록 레이아웃을 재정 CardView 의할 수 있습니다.

<ContentPage.Resources>
    <ResourceDictionary>
        <ControlTemplate x:Key="CardViewCompressed">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="100" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100" />
                    <ColumnDefinition Width="100*" />
                </Grid.ColumnDefinitions>
                <Image Grid.Row="0"
                       Grid.Column="0"
                       Source="{TemplateBinding IconImageSource}"
                       BackgroundColor="{TemplateBinding IconBackgroundColor}"
                       WidthRequest="100"
                       HeightRequest="100"
                       Aspect="AspectFill"
                       HorizontalOptions="Center"
                       VerticalOptions="Center"/>
                <StackLayout Grid.Row="0"
                             Grid.Column="1">
                    <Label Text="{TemplateBinding CardTitle}"
                           FontAttributes="Bold" />
                    <Label Text="{TemplateBinding CardDescription}" />
                </StackLayout>
            </Grid>
        </ControlTemplate>
    </ResourceDictionary>
</ContentPage.Resources>

데이터 바인딩은 ControlTemplate 태그 확장을 사용하여 TemplateBinding 바인딩을 지정합니다. 그런 다음 해당 ControlTemplate 값을 사용하여 x:Key 정의된 ControlTemplate 개체로 속성을 설정할 수 있습니다. 다음 예제에서는 인스턴스에 ControlTemplate 설정된 속성을 보여 줍니다 CardView .

<controls:CardView ControlTemplate="{StaticResource CardViewCompressed}"/>

다음 스크린샷은 표준 CardView 인스턴스와 CardViewControlTemplate 재정의된 인스턴스를 보여 줍니다.

CardView ControlTemplate screenshot

컨트롤 템플릿에 대한 자세한 내용은 Xamarin.Forms 컨트롤 템플릿을 참조하세요.