의 동적 스타일 Xamarin.Forms

Download Sample 샘플 다운로드

스타일은 속성 변경에 응답하지 않으며 애플리케이션 기간 동안 변경되지 기본. 예를 들어 Visual 요소에 Style을 할당한 후 Setter 인스턴스 중 하나가 수정, 제거 또는 새 Setter 인스턴스가 추가된 경우 변경 내용이 시각적 요소에 적용되지 않습니다. 그러나 애플리케이션은 동적 리소스를 사용하여 런타임 시 스타일 변경에 동적으로 응답할 수 있습니다.

태그 확장은 DynamicResource 둘 다 사전 키를 사용하여 값을 가져오는 ResourceDictionary태그 확장과 유사 StaticResource 합니다. 그러나 단일 사전 조회 DynamicResource 를 수행하는 동안 StaticResource 기본 사전 키에 대한 링크를 가져옵니다. 따라서 키와 연결된 사전 항목이 바뀌면 변경 내용이 시각적 요소에 적용됩니다. 이렇게 하면 애플리케이션에서 런타임 스타일을 변경할 수 있습니다.

다음 코드 예제에서는 XAML 페이지의 동적 스타일을 보여 줍니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.DynamicStylesPage" Title="Dynamic" IconImageSource="xaml.png">
    <ContentPage.Resources>
        <ResourceDictionary>
            <Style x:Key="baseStyle" TargetType="View">
              ...
            </Style>
            <Style x:Key="blueSearchBarStyle"
                   TargetType="SearchBar"
                   BasedOn="{StaticResource baseStyle}">
              ...
            </Style>
            <Style x:Key="greenSearchBarStyle"
                   TargetType="SearchBar">
              ...
            </Style>
            ...
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout Padding="0,20,0,0">
            <SearchBar Placeholder="These SearchBar controls"
                       Style="{DynamicResource searchBarStyle}" />
            ...
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

인스턴스는 SearchBar 태그 확장을 사용하여 DynamicResource XAML에 정의되지 않은 명명된 이름을 searchBarStyle참조 Style 합니다. 그러나 인스턴스의 SearchBar 속성이 Style aDynamicResource를 사용하여 설정되므로 누락된 사전 키로 인해 예외가 throw되지는 않습니다.

대신 코드 숨김 파일에서 생성자는 다음 코드 예제와 같이 키를 searchBarStyle사용하여 항목을 만듭니다ResourceDictionary.

public partial class DynamicStylesPage : ContentPage
{
    bool originalStyle = true;

    public DynamicStylesPage ()
    {
        InitializeComponent ();
        Resources ["searchBarStyle"] = Resources ["blueSearchBarStyle"];
    }

    void OnButtonClicked (object sender, EventArgs e)
    {
        if (originalStyle) {
            Resources ["searchBarStyle"] = Resources ["greenSearchBarStyle"];
            originalStyle = false;
        } else {
            Resources ["searchBarStyle"] = Resources ["blueSearchBarStyle"];
            originalStyle = true;
        }
    }
}

OnButtonClicked 이벤트 처리기가 실행되면 searchBarStyle 간에 blueSearchBarStyle 전환됩니다greenSearchBarStyle. 이로 인해 결국 다음 스크린샷에 표시된 모양이 됩니다.

Blue Dynamic Style ExampleGreen Dynamic Style Example

다음 코드 예제에서는 C#의 해당 페이지를 보여 줍니다.

public class DynamicStylesPageCS : ContentPage
{
    bool originalStyle = true;

    public DynamicStylesPageCS ()
    {
        ...
        var baseStyle = new Style (typeof(View)) {
            ...
        };
        var blueSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        var greenSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        ...
        var searchBar1 = new SearchBar { Placeholder = "These SearchBar controls" };
        searchBar1.SetDynamicResource (VisualElement.StyleProperty, "searchBarStyle");
        ...
        Resources = new ResourceDictionary ();
        Resources.Add ("blueSearchBarStyle", blueSearchBarStyle);
        Resources.Add ("greenSearchBarStyle", greenSearchBarStyle);
        Resources ["searchBarStyle"] = Resources ["blueSearchBarStyle"];

        Content = new StackLayout {
            Children = { searchBar1, searchBar2, searchBar3, searchBar4,    button    }
        };
    }
    ...
}

C#에서 인스턴스는 SearchBar 메서드를 SetDynamicResource 사용하여 참조 searchBarStyle합니다. OnButtonClicked 이벤트 처리기 코드는 XAML 예제와 동일하며 실행될 searchBarStyle 때 사이 blueSearchBarStyle 를 전환합니다greenSearchBarStyle.

동적 스타일 상속

속성을 사용하여 Style.BasedOn 동적 스타일에서 스타일을 파생할 수 없습니다. 대신 클래스에는 Style 값이 BaseResourceKey 동적으로 변경될 수 있는 사전 키로 설정할 수 있는 속성이 포함됩니다.

다음 코드 예제에서는 XAML 페이지의 동적 스타일 상속을 보여 줍니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Styles.DynamicStylesInheritancePage" Title="Dynamic Inheritance" IconImageSource="xaml.png">
    <ContentPage.Resources>
        <ResourceDictionary>
            <Style x:Key="baseStyle" TargetType="View">
              ...
            </Style>
            <Style x:Key="blueSearchBarStyle" TargetType="SearchBar" BasedOn="{StaticResource baseStyle}">
              ...
            </Style>
            <Style x:Key="greenSearchBarStyle" TargetType="SearchBar">
              ...
            </Style>
            <Style x:Key="tealSearchBarStyle" TargetType="SearchBar" BaseResourceKey="searchBarStyle">
              ...
            </Style>
            ...
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout Padding="0,20,0,0">
            <SearchBar Text="These SearchBar controls" Style="{StaticResource tealSearchBarStyle}" />
            ...
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

인스턴스는 SearchBar 태그 확장을 사용하여 StaticResource 명명tealSearchBarStyle된 을 Style 참조합니다. 이렇게 하면 Style 몇 가지 추가 속성이 설정되고 이 속성이 BaseResourceKey 참조 searchBarStyle됩니다. DynamicResource 태그 확장은 파생되는 경우를 제외하고 Style 변경되지 않으므로 필요하지 tealSearchBarStyle 않습니다. 따라서 tealSearchBarStyle 기본에 대한 링크를 searchBarStyle 클릭하여 기본 스타일이 변경될 때 변경됩니다.

코드 숨김 파일에서 생성자는 동적 스타일을 보여 준 이전 예제에 따라 키를 searchBarStyle사용하여 항목을 만듭니다ResourceDictionary. OnButtonClicked 이벤트 처리기가 실행되면 searchBarStyle 간에 blueSearchBarStyle 전환됩니다greenSearchBarStyle. 이로 인해 결국 다음 스크린샷에 표시된 모양이 됩니다.

Blue Dynamic Style Inheritance ExampleGreen Dynamic Style Inheritance Example

다음 코드 예제에서는 C#의 해당 페이지를 보여 줍니다.

public class DynamicStylesInheritancePageCS : ContentPage
{
    bool originalStyle = true;

    public DynamicStylesInheritancePageCS ()
    {
        ...
        var baseStyle = new Style (typeof(View)) {
            ...
        };
        var blueSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        var greenSearchBarStyle = new Style (typeof(SearchBar)) {
            ...
        };
        var tealSearchBarStyle = new Style (typeof(SearchBar)) {
            BaseResourceKey = "searchBarStyle",
            ...
        };
        ...
        Resources = new ResourceDictionary ();
        Resources.Add ("blueSearchBarStyle", blueSearchBarStyle);
        Resources.Add ("greenSearchBarStyle", greenSearchBarStyle);
        Resources ["searchBarStyle"] = Resources ["blueSearchBarStyle"];

        Content = new StackLayout {
            Children = {
                new SearchBar { Text = "These SearchBar controls", Style = tealSearchBarStyle },
                ...
            }
        };
    }
    ...
}

인스턴스 tealSearchBarStyleSearchBar 속성에 Style 직접 할당됩니다. 이렇게 하면 Style 몇 가지 추가 속성이 BaseResourceKey 설정되고 이 속성을 사용하여 참조 searchBarStyle합니다. SetDynamicResource 이 메서드는 파생되는 경우를 제외하고 Style 변경되지 않으므로 여기서 tealSearchBarStyle 는 필요하지 않습니다. 따라서 tealSearchBarStyle 기본에 대한 링크를 searchBarStyle 클릭하여 기본 스타일이 변경될 때 변경됩니다.

Channel 9YouTube에서 더 많은 Xamarin 비디오를 확인하세요.