【问题标题】:Colour multiple textboxes with one method wpf使用一种方法 wpf 为多个文本框着色
【发布时间】:2017-10-11 23:00:43
【问题描述】:

我有一个方法应该为焦点上的文本框的背景着色(Enter)

 private void onEnter_ColourChange(object sender, EventArgs e)
    {
        this.BackColor = Color.White;
    }

但是,这不起作用。我检查了这个answer,但我得到了一个 NullReferenceException。

基本上,当文本框处于焦点时,我想用一种方法为多个文本框着色。有没有办法做到这一点?

【问题讨论】:

  • 没有看到你的其余代码,我有预感你正在寻找(sender as TextBox).BackColor = Color.White;
  • 不,我将代码更改为 Textbox textbox = sender as Textbox textbox.BackColour = Color.White 这就是我得到 NullReferenceException 的地方。
  • 如果您收到 NullReferenceException,听起来发件人不是文本框
  • 您应该使用样式来代替。这样你不会得到任何空引用异常。
  • @zambonee,这不起作用(如果这是一个建议)

标签: c# .net wpf visual-studio


【解决方案1】:

首先:TextBox只有Background属性,没有BackColor!

如果你想改变焦点文本框的颜色,一个简单的方法是使用带有触发器的样式。

<Window.Resources>
    <Style TargetType="TextBox" x:Key="TextBoxFocusBackgroundStyle" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="true" >
                <Setter Property="Background" Value="Brown" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

如您所见,触发器监视属性 IsFocused。如果 TextBox 获得焦点(因此 IsFocused 更改为 true),则背景将为棕色。

要使用这种风格:

<StackPanel>
    <TextBox Text="Peter" Style="{StaticResource TextBoxFocusBackgroundStyle}"/>
    <TextBox Text="Laszlo" Style="{StaticResource TextBoxFocusBackgroundStyle}"/>
    <TextBox Text="Julia" Style="{StaticResource TextBoxFocusBackgroundStyle}"/>
    <TextBox Text="Romeo" Style="{StaticResource TextBoxFocusBackgroundStyle}"/>
</StackPanel>

如果您已经有文本框的样式,您应该在 BasedOn 属性中使用该样式。

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多