如何从C#代码访问全局样式的元素?

问题描述 投票:0回答:1

我想对文本框使用全局样式,如果单击按钮时文本框为空,则更改文本框的颜色。到目前为止我已经写了这些:

应用程序.xaml


<Application x:Class="MVPInterface.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:MVPInterface"
             StartupUri="TheTestWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <Style x:Key="NameTextField" TargetType="TextBox">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TextBox}">
                            <TextBox BorderThickness="0,0,0,3" Background="White">
                                <TextBox.BorderBrush>
                                    <SolidColorBrush x:Name="NameFieldColor" Color="#FFC3C3C3"/>
                                </TextBox.BorderBrush>
                            </TextBox>
                            <ControlTemplate.Resources>
                                <Storyboard x:Key="gotFocusTimeline">
                                    <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="NameFieldColor" Storyboard.TargetProperty="(SolidColorBrush.Color)">
                                        <LinearColorKeyFrame KeyTime="00:00:00.30" Value="#ff007fc7"/>
                                    </ColorAnimationUsingKeyFrames>
                                </Storyboard>
                                <Storyboard x:Key="lostFocusTimeline">
                                    <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="NameFieldColor" Storyboard.TargetProperty="(SolidColorBrush.Color)">
                                        <LinearColorKeyFrame KeyTime="00:00:00.30" Value="#FFC3C3C3"/>
                                    </ColorAnimationUsingKeyFrames>
                                </Storyboard>
                            </ControlTemplate.Resources>
                            <ControlTemplate.Triggers>
                                <EventTrigger RoutedEvent="GotFocus">
                                    <BeginStoryboard Storyboard="{StaticResource gotFocusTimeline}"/>
                                </EventTrigger>

                                <EventTrigger RoutedEvent="LostFocus">
                                    <BeginStoryboard Storyboard="{StaticResource lostFocusTimeline}"/>
                                </EventTrigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</Application>

TheTestWindow.xaml


<Window x:Class="MVPInterface.TheTestWindow"
        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:MVPInterface"
        mc:Ignorable="d"
        Title="The Screen" Height="1080" Width="1920" AllowsTransparency="True" WindowStyle="None" Background="{x:Null}" ResizeMode="CanMinimize" WindowState="Maximized">
    <Border Name="theWindow" CornerRadius="10" Background="Azure" BorderBrush="Gray" BorderThickness="3" ScrollViewer.VerticalScrollBarVisibility="Disabled" Focusable="True">
        <Grid>
            <TextBox Grid.Row="2" Name="myTextbox" Text="Tester" MinWidth="100" Width="320" Background="White" GotFocus="OnGotFocusBox" LostFocus="OnLostFocusBox" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource NameTextField}"/>
            <Button Grid.Row="2" Name="mySubmitButton" Width="100" Height="25" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,120,0,0" Click="TestClick" Style="{StaticResource GrayDefaultButtonStyle}">
        </Grid>
    </Border>
</Window>

TheTestWindow.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Windows;
using System.Windows.Controls;


namespace MVPInterface
{   
    public partial class TheTestWindow : Window
    {
    
        Color fieldGray = Color.FromArgb(255, 195, 195, 195);
        Color fieldBlue = Color.FromArgb(255, 0, 127, 199);
        Color fieldPurple = Color.FromArgb(255, 126, 42, 144);

        public TheTestWindow()
        {

            InitializeComponent();
            
        }

        private void TestClick(object sender, RoutedEventArgs e)
        {

            if (myTextbox.Text == null || myTextbox.Text.Text == "" || myTextbox.Text.Text[0].Equals(" "))
            {

                ColorAnimation colorAnimationError = new ColorAnimation(fieldPurple, TimeSpan.FromSeconds(0.3));
                NameFieldColor.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimationError);

           }

        private void MouseDrag(object sender, MouseButtonEventArgs e)
        {

            try
            {

                DragMove();

            }

            catch(Exception) 
            {

                MessageBox.Show("An exception ocurred...");
    
            }

        }

        private void WindowClicked(object sender, MouseButtonEventArgs e)
        {

            theWindow.Focus();

        }

但是,我看到一个错误,告诉我 TheTestWindow.xaml.cs 中的 NameFieldColor 不存在。我想知道如何从我的后台代码TheTestWindow.xaml.cs访问我在App.xaml中定义的NameFieldColor

  • 奖金:

我还有一件事很好奇:将按钮的样式设置为全局样式后,为什么我不能使用 content 在按钮上显示文本?如果我想在多个按钮上使用这种样式,每个按钮内部应该有不同的文本,我该如何实现呢?

c# wpf xaml
1个回答
0
投票

TextBox 的 ControlTemplate 中的 TextBox 没有意义。应该有一个带有

<ScrollViewer x:Name="PART_ContentHost"/>
子元素的边框。

但是,您的 Style 根本不需要 ControlTemplate。这应该足够了:

<Application.Resources>
    <Style x:Key="NameTextField" TargetType="TextBox">
        <Setter Property="BorderBrush" Value="#C3C3C3"/>
        <Setter Property="BorderThickness" Value="2"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <ScrollViewer x:Name="PART_ContentHost"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="BorderBrush" Value="#007FC7"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Application.Resources>

由于此类全局 Style 的元素无法进行动画处理,因此当您想要启动“错误边框”动画时,必须临时设置一个新的 BorderBrush:

if (string.IsNullOrWhiteSpace(myTextbox.Text))
{
    var colorAnimationError = new ColorAnimation(
        fieldPurple, TimeSpan.FromSeconds(0.3));
    var borderBrush = myTextbox.BorderBrush.Clone();

    myTextbox.SetCurrentValue(TextBox.BorderBrushProperty, borderBrush);
    borderBrush.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimationError);
}
© www.soinside.com 2019 - 2024. All rights reserved.