본문 바로가기

Programming/Xamarin

Xamarin forms ContentView 사용 예제 Control Customizing

반응형

ContentView를 만들고 다른 뷰에서 마치 커스터마이징된 Control처럼 사용할 수 있다.

아래에선 Image들과 Label이 하나 있는 ContentView를 만들고 Page에 적용해본다.


1. ContentView들을 담을 폴더를 하나 만든다.


2. 새로만든 폴더에 ContentView를 하나 추가한다. 


3. 설계한 ContentView를 만든다. 

예제는 아래와 같이 좌측에 대표이미지, 우측 상단에 간단한 텍스트 및 우측 하단에 상태를 표시해줄 이미지

총 3개의 컨트롤로 ContentView를 구성했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <ContentView.Content>
        <Frame HeightRequest="100" HorizontalOptions="Center" VerticalOptions="Center" Padding="10" Margin="10" BackgroundColor="Black">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="2*"/>
                </Grid.ColumnDefinitions>
 
                <Image Grid.Column="0" Source="Android.jpg"/>
                <StackLayout Grid.Column="1">
                    <Label x:Name="MainLabel" Text="Text" FontSize="28" HorizontalOptions="Center" VerticalOptions="Center"/>
                    <Image Source="Android.jpg" WidthRequest="50" HeightRequest="50" VerticalOptions="Center"/>
                </StackLayout>
            </Grid>
        </Frame>
    </ContentView.Content>
</ContentView>
cs


xaml 디자인탭에서 랜더링 된 결과는 아래와 같다.



4. ContentView의 CodeBehind로 이동하여 바깥으로 노출시킬 내부 Control들의 Option을 프로퍼티로 만들어준다.

아래 예시에선 ContentView 내부의 Label의 Text값을 프로퍼티로 만들어 외부에서 변경이 가능하도록 하였다.

1
2
3
4
5
6
7
8
9
10
11
12
13
    public partial class ImageContentView : ContentView
    {
        public ImageContentView ()
        {
            InitializeComponent ();
        }
 
        public string Text
        {
            get { return MainLabel.Text; }
            set { MainLabel.Text = value; }
        }
    }
cs


5. 이제 ContentView를 사용할 Page에서 namespace를 선언해준다. 변수명은 cv(content views)로 하였다.

이후 사용할 위치에서 아래와 같이 ContentView를 선언하고 필요한 option을 설정해준다.

(위에서 밖으로 노출시켰던 ContentView 내부 Label의 Text를 Set 해주었다.)

1
2
3
4
5
6
7
<ScrollView x:Name="LocationScrollView" Margin="10" Padding="10">
<StackLayout>
     <cv:ImageContentView Text="FirstText"/>
        <cv:ImageContentView Text="SecondText"/>
       <cv:ImageContentView Text="ThridText"/>
    </StackLayout>
</ScrollView>
cs


아래는 xaml 디자인탭에서 랜더링 된 결과이다.

ScrollView안에 ContentView들이 잘 들어가 있음을 확인할 수 있다.





반응형