简体   繁体   中英

WPF Dynamic Style Control

I created a TabControl. Inside it I want every "Page" to have a different styling. So I tryed to mess a little bit up with ContentType. Now if I use a static reference it works just fine but what I was trying to do is to do something dynamic. So I was thinking about inserting a string in the class I was giving to the tabcontrol (List_OpenPage.ItemSource = pages) a value like Home. Then I set the ContentTemplate as follow {StaticResource ResourceKey={Binding Style}} where Style is a reference to the List called page. (indeed if I call list.page i should get a string like home or test). This idea doesnt work.. So do you have any idea how to make it work?

   <TabControl Name="List_OpenPage" BorderThickness="0" Style="{DynamicResource TabControlStyle1}"  ContentTemplate="{StaticResource Home}">
            <TabControl.Resources>
                <SolidColorBrush x:Key="TabItem.Selected.Background" Color="LightGray"/>
                <SolidColorBrush x:Key="TabItem.Selected.Border" Color="#ACACAC"/>
                <Style x:Key="TabControlStyle1" TargetType="{x:Type TabControl}">
        // Some ignorable styling \\
                </Style>
            </TabControl.Resources>

            <TabControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Title}" Margin="2" FontSize="13"/>
                </DataTemplate>
            </TabControl.ItemTemplate>

        </TabControl>

-- Data Templates

  <Window.Resources>
    
   <DataTemplate x:Key="Home">
        <ListView ItemsSource="{Binding Datas}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="Red">


         </ListView>

    </DataTemplate>

    <DataTemplate x:Key="test">
        <ListView ItemsSource="{Binding Datas}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Background="LightGray">


        </ListView>
    </DataTemplate>
  </Window.Resources>
        

//

public class Page
{
    public string Title { get; set; }
    public string Style { get; set; } (will be home or test for this example)
    public List<Result.Data> Datas { get; set; }


}

The way to do this would be to define a DataTemplateSelector and use the TabControl.ContentTemplateSelector property, eg:

public class CustomTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        if (item is Page page)
            return Application.Current.MainWindow?.FindResource(page.Style) as DataTemplate;

        return null;
    }
}

XAML:

<TabControl ...>
    <TabControl.ContentTemplateSelector>
        <local:CustomTemplateSelector />
    </TabControl.ContentTemplateSelector>
</TabControl>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM