简体   繁体   English

为动态生成的 WPF 控件分配模板

[英]Assigning templates to dynamically generated WPF controls

In an application, I need to remove the default highlighting effect applied to buttons when the mouse is over them.在应用程序中,当鼠标悬停在按钮上时,我需要删除应用于按钮的默认突出显示效果。 I understand this effect can be achieved by creating a custom template without the highlight feature and applying it to your buttons.我知道可以通过创建一个没有突出显示功能的自定义模板并将其应用于您的按钮来实现这种效果。 However, I don't know how many buttons are needed until runtime and therefore cannot explicitly set the template property beforehand in the xaml file.但是,直到运行时我才知道需要多少按钮,因此无法事先在 xaml 文件中显式设置模板属性。

I tried setting the template as you would in the xaml file: Template = "{StaticResource MyButtonTemplate}" when I created the object but this did not work.我尝试在 xaml 文件中设置模板: Template = "{StaticResource MyButtonTemplate}"当我创建对象时,但这不起作用。

How can I set the template of a new Button object to a template that I specified in the xaml file?如何将新 Button 对象的模板设置为我在 xaml 文件中指定的模板? (I have heard that templates can be defined in C# but would like to avoid this if possible as I heard it is extremely tedious). (我听说可以在 C# 中定义模板,但我希望尽可能避免这种情况,因为我听说它非常乏味)。

It sounds like you could use a DataTemplate to achieve what you want.听起来您可以使用DataTemplate来实现您想要的。

You could set the style property of the template and then that would apply to any button that you added to the list that the template is bound to.您可以设置模板的 style 属性,然后这将应用于您添加到模板绑定到的列表中的任何按钮。

Here's a quick example that I made (It's not using bindings because it's kind of late here but I'm sure you can work that part out)这是我制作的一个快速示例(它没有使用绑定,因为这里有点晚,但我相信你可以解决这个问题)

MainWindow.xaml主窗口.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox x:Name="listBox" ItemsSource="{Binding}" BorderBrush="Transparent" HorizontalContentAlignment="Stretch">

            <!--Remove the hover and select style of the list view because we aren't using the list in that way-->
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="FontSize" Value="12"/>
                    <Setter Property="FontFamily" Value="Arial"/>
                    <Setter Property="Padding" Value="3"/>
                    <Setter Property="HorizontalContentAlignment" Value="Left"/>
                    <Setter Property="VerticalContentAlignment" Value="Top"/>
                    <Setter Property="Background" Value="Transparent"/>
                    <Setter Property="BorderThickness" Value="0"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="ListBoxItem">
                                <Grid Background="{TemplateBinding Background}">
                                    <VisualStateManager.VisualStateGroups>
                                        <VisualStateGroup x:Name="CommonStates">
                                            <VisualState x:Name="Normal"/>
                                            <VisualState x:Name="MouseOver">
                                                <Storyboard>
                                                    <DoubleAnimation Duration="0" To=".35" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor"/>
                                                </Storyboard>
                                            </VisualState>
                                            <VisualState x:Name="Disabled">
                                                <Storyboard>
                                                    <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="contentPresenter"/>
                                                </Storyboard>
                                            </VisualState>
                                        </VisualStateGroup>
                                        <VisualStateGroup x:Name="SelectionStates">
                                            <VisualState x:Name="Unselected"/>
                                            <VisualState x:Name="Selected"/>
                                        </VisualStateGroup>
                                        <VisualStateGroup x:Name="FocusStates">
                                            <VisualState x:Name="Focused"/>
                                            <VisualState x:Name="Unfocused"/>
                                        </VisualStateGroup>
                                    </VisualStateManager.VisualStateGroups>
                                    <Rectangle x:Name="fillColor" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                                    <Rectangle x:Name="fillColor2" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
                                    <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"/>
                                    <Rectangle x:Name="FocusVisualElement" RadiusY="1" RadiusX="1" StrokeThickness="1" Visibility="Collapsed"/>
                                </Grid>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>

            <!--Setup the design that we have for our buttons-->
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid Margin="4">
                        <Button Content="{Binding}" FontWeight="Bold"  >
                            <Button.Style>
                                <Style TargetType="{x:Type Button}">
                                    <Setter Property="Template">
                                        <Setter.Value>
                                            <ControlTemplate TargetType="{x:Type Button}">
                                                <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                                                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                                </Border>
                                            </ControlTemplate>
                                        </Setter.Value>
                                    </Setter>
                                    <Style.Triggers>
                                        <Trigger Property="IsMouseOver" Value="True">
                                            <Setter Property="Background" Value="Red"/>
                                        </Trigger>
                                    </Style.Triggers>
                                </Style>
                            </Button.Style>
                        </Button>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

MainWindow.xaml.cs主窗口.xaml.cs

using System;
using System.Collections.Generic;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        List<string> items = new List<string>();


        public MainWindow()
        {
            InitializeComponent();

            //Add the buttons to the list
            items.Add("test");
            items.Add("test1");
            items.Add("test2");
            items.Add("test3");

            //Update the item source of the list view
            //This should probably be done properly with bindings but the main question was about the xaml
            listBox.ItemsSource = items;
        }
    }
}

And here you can see the result在这里你可以看到结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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