以自定义方式访问 ControlTemplate 样式 Application.Resources

Accessing ControlTemplate Style In Custom Application.Resources

我已经为我想为项目中的每个相册调用的按钮创建了模板样式。

<Application.Resources>
    <Style x:Key="CustomButtonLarge" TargetType="Button">
        <Setter Property="Background" Value="Pink" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="Width" Value="300" />
        <Setter Property="Height" Value="100" />
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="VerticalAlignment" Value="Top" />
        <Setter Property="Height" Value="300" />
        <Setter Property="Width" Value="200" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid x:Name="AlbumContentGrid">

                        <Grid.RowDefinitions>
                            <RowDefinition Height="200"/>
                            <RowDefinition Height="50"/>
                            <RowDefinition Height="50"/>
                        </Grid.RowDefinitions>

                        <Image Grid.Row="0" source="null" x:Key="albumCover" />
                        <Textblock Grid.Row="1" x:Key="Title" Style="{StaticResources CustomForegroundTitleText}"/>
                        <Textblock Grid.Row="2" x:Key="SubTitle" Style="{StaticResources CustomForegroundSubTitleText}" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>


</Application.Resources>

当我在后面的代码中时,我想为每个相册创建这个按钮。所以如果有 3 张专辑,我想做一个 for 循环...

int numberOfButtons= 3;

private void Page_Loaded(object sender, RoutedEventArgs e)
    {

        for (int i = 0; i < numberOfButtons; i++)
        {
            Button btn = new Button();
            Style style = App.Current.Resources["CustomButtonLarge"] as Style;

            btn.Style = style;

            StackAlbums.Children.Add(btn);
        }

    }

StackAlbums 是主网格中的一个 stackPanel。出于某种原因,当我 运行.

时我没有得到任何东西

但我也不确定如何访问 "albumCover" 图片,以便我可以将源更改为代码中我需要的任何内容,并更改标题和副标题文本块的文本值.

首先,您应该修复 Style 有重复的 属性 widthHeight.

那你应该做背景的效果。你应该将它绑定到 Grid。

                    <Grid x:Name="AlbumContentGrid" Background="{TemplateBinding Background}" >

应将网格设置为 Background 以绑定 Button 背景。

并且您应该删除所有 x:Key

如果您想在代码中设置图像,您应该创建数据上下文。

我做了一个classFoo来做。

public class Foo
{
    public BitmapImage Image { get; set; }

    public string Title { get; set; }

    public string  SubTitle { get; set; }
}

而且我应该在添加按钮的时候设置它。

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        int numberOfButtons = 3;


        for (int i = 0; i < numberOfButtons; i++)
        {
            var foo = new Foo
            {
                Image = new BitmapImage(new Uri("ms-appx:///Assets/Square44x44Logo.scale-200.png")),
                Title = "title" + i,
                SubTitle = i.ToString()
            };

            Button btn = new Button();
            Style style = Application.Current.Resources["CustomButtonLarge"] as Style;

            btn.Style = style;

            btn.DataContext = foo;

            StackAlbums.Children.Add(btn);
        }
    }

代码使用Square44x44Logo.scale-200.png,您可以更改它。

然后我应该使用 bind 来绑定数据上下文,CustomButtonLarge 的所有代码都是

<Application.Resources>
    <Style x:Key="CustomButtonLarge" TargetType="Button">
        <Setter Property="Background" Value="Black" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="HorizontalAlignment" Value="Center" />
        <Setter Property="VerticalAlignment" Value="Top" />
        <Setter Property="Margin" Value="10,10,10,10"></Setter>
        <Setter Property="Height" Value="200" />
        <Setter Property="Width" Value="100" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button" >
                    <Grid x:Name="AlbumContentGrid" Background="{TemplateBinding Background}" >
                        <Grid.RowDefinitions>
                            <RowDefinition Height="200*"/>
                            <RowDefinition Height="50*"/>
                            <RowDefinition Height="50*"/>
                        </Grid.RowDefinitions>

                        <Image Grid.Row="0" x:Name="AlbumCover" Source="{Binding Path=Image}"/>
                        <TextBlock Grid.Row="1" x:Name="Title" Text="{Binding Title}" Foreground="{TemplateBinding Foreground}"/>
                        <TextBlock Grid.Row="2" x:Name="SubTitle" Text="{Binding SubTitle}" Foreground="{TemplateBinding Foreground}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Application.Resources>

我尝试运行它并把屏幕截图给你。

如果你想添加点击事件,你应该添加一些代码。

        for (int i = 0; i < numberOfButtons; i++)
        {
            var foo = new Foo
            {
                Image = new BitmapImage(new Uri("ms-appx:///Assets/Square44x44Logo.scale-200.png")),
                Title = "title" + i,
                SubTitle = i.ToString()
            };

            Button btn = new Button();
            Style style = Application.Current.Resources["CustomButtonLarge"] as Style;

            btn.Style = style;

            btn.DataContext = foo;

            StackAlbums.Children.Add(btn);

            btn.Click += Button_OnClick; // Make the click
        }

你应该写 Button_OnClick 并添加断点以了解用户单击按钮。

    private void Button_OnClick(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine(StackAlbums.Children.Count);
        Debug.WriteLine((StackAlbums.Children[0] as FrameworkElement)?.ActualWidth );
        Debug.WriteLine((StackAlbums.Children[0] as Button)?.Background?.ToString() ?? "");
    }

编辑

如果你想添加点击动画,你应该将代码添加到VisualStateManager.VisualStateGroups

                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal">
                                <Storyboard>
                                    <PointerUpThemeAnimation Storyboard.TargetName="AlbumContentGrid" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="PointerOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="AlbumContentGrid"
                                                                   Storyboard.TargetProperty="BorderBrush">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="{ThemeResource SystemControlHighlightBaseMediumLowBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Title"
                                                                   Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="#aaaaaa" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="SubTitle"
                                                                   Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0"
                                                                Value="#aaaaaa" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <PointerUpThemeAnimation Storyboard.TargetName="AlbumContentGrid" />
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="AlbumContentGrid"
                                                                   Storyboard.TargetProperty="Background">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseMediumLowBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="AlbumContentGrid"
                                                                   Storyboard.TargetProperty="BorderBrush">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightTransparentBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Title"
                                                                   Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="SubTitle"
                                                                   Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}" />
                                    </ObjectAnimationUsingKeyFrames>
                                    <PointerDownThemeAnimation Storyboard.TargetName="AlbumContentGrid" />
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>

您应该像下图一样将代码添加到 AlbumContentGrid。

添加代码即可看到点击动画