programing

XAML 에서 범용 타입을 지정할 수 있습니까(전).NET 4 프레임워크)?

easyjava 2023. 4. 19. 23:35
반응형

XAML 에서 범용 타입을 지정할 수 있습니까(전).NET 4 프레임워크)?

XAML에서는 DataTemplate를 선언하여 특정 유형이 표시될 때마다 템플릿을 사용할 수 있습니다.예를 들어, 이 DataTemplate는 TextBlock을 사용하여 고객의 이름을 표시합니다.

<DataTemplate DataType="{x:Type my:Customer}">
    <TextBlock Text="{Binding Name}" />
</DataTemplate>

IList <고객명>이 표시될 때마다 사용할 Data Template를 정의할 수 있는지 궁금합니다.따라서 ContentControl의 콘텐츠가 관찰 가능한 컬렉션 <고객>인 경우 해당 템플릿을 사용합니다.

{x:}를 사용하여 XAML의 IList와 같은 범용 유형을 선언할 수 있습니까?Type} 마크업 확장자를 지정하시겠습니까?

XAML에서는 직접 사용할 수 없지만DataTemplateSelector올바른 템플릿을 선택합니다.

public class CustomerTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item,
                                                DependencyObject container)
    {
        DataTemplate template = null;
        if (item != null)
        {
            FrameworkElement element = container as FrameworkElement;
            if (element != null)
            {
                string templateName = item is ObservableCollection<MyCustomer> ?
                    "MyCustomerTemplate" : "YourCustomerTemplate";

                template = element.FindResource(templateName) as DataTemplate;
            } 
        }
        return template;
    }
}

public class MyCustomer
{
    public string CustomerName { get; set; }
}

public class YourCustomer
{
    public string CustomerName { get; set; }
}

리소스 사전:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    >
    <DataTemplate x:Key="MyCustomerTemplate">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="150"/>
            </Grid.RowDefinitions>
            <TextBlock Text="My Customer Template"/>
            <ListBox ItemsSource="{Binding}"
                     DisplayMemberPath="CustomerName"
                     Grid.Row="1"/>
        </Grid>
    </DataTemplate>

    <DataTemplate x:Key="YourCustomerTemplate">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="150"/>
            </Grid.RowDefinitions>
            <TextBlock Text="Your Customer Template"/>
            <ListBox ItemsSource="{Binding}"
                     DisplayMemberPath="CustomerName"
                     Grid.Row="1"/>
        </Grid>
    </DataTemplate>
</ResourceDictionary>

XAML 창:

<Window 
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" 
    Height="300" 
    Width="300"
    xmlns:local="clr-namespace:WpfApplication1"
    >
    <Grid>
        <Grid.Resources>
            <local:CustomerTemplateSelector x:Key="templateSelector"/>
        </Grid.Resources>
        <ContentControl 
            Content="{Binding}" 
            ContentTemplateSelector="{StaticResource templateSelector}" 
            />
    </Grid>
</Window>

뒤에 있는 창 코드:

public partial class Window1
{
    public Window1()
    {
        InitializeComponent();
        ObservableCollection<MyCustomer> myCustomers
            = new ObservableCollection<MyCustomer>()
        {
            new MyCustomer(){CustomerName="Paul"},
            new MyCustomer(){CustomerName="John"},
            new MyCustomer(){CustomerName="Mary"}
        };

        ObservableCollection<YourCustomer> yourCustomers
            = new ObservableCollection<YourCustomer>()
        {
            new YourCustomer(){CustomerName="Peter"},
            new YourCustomer(){CustomerName="Chris"},
            new YourCustomer(){CustomerName="Jan"}
        };
        //DataContext = myCustomers;
        DataContext = yourCustomers;
    }
}

바로 사용할 수 있는 것은 아닙니다.하지만, 이미 그렇게 하고 있는 기업형 개발자가 있습니다.

를 들면, 이 투고에서는, Microsoft의 Mike Hillberg가 이것을 사용하고 있었습니다.물론 구글에는 다른 것도 있다.

범용 클래스를 T를 지정하는 파생 클래스로 랩할 수도 있습니다.

public class StringList : List<String>{}

및 XAML의 StringList를 사용합니다.

aelij(WPF 기여 프로젝트의 프로젝트 코디네이터)에게는 다른 방법이 있습니다.

더욱 쿨한 것은 (앞으로 휴무일지라도) XAML 2009(XAML 2006은 현재 버전)가 이를 네이티브로 지원한다는 점입니다.자세한 내용은 이 PDC 2008 세션을 참조하십시오.

범용의 목적은 완전히 무시되지만 XAML에서 해당 유형을 사용할 수 있는 유일한 목적으로 이와 같은 범용에서 파생된 클래스를 정의할 수 있습니다.

public class MyType : List<int> { }

xaml에 사용합니다. 예를 들어 다음과 같습니다.

<DataTemplate DataType={x:Type myNamespace:MyType}>

언급URL : https://stackoverflow.com/questions/185349/can-i-specify-a-generic-type-in-xaml-pre-net-4-framework

반응형