【问题标题】:Change WPF Textbox Foreground Color on Event在事件上更改 WPF 文本框前景色
【发布时间】:2014-05-19 03:56:49
【问题描述】:

我想根据传入的事件(传入的数字与文本框中的数字不同)更改文本框的前景色,但如果通过 UI 更改了任何文本,则将其改回黑色。我有这个以迂回的方式工作,但我不确定正确的方法。

XAML:

<TextBox Style="{StaticResource recParm}" Foreground="{Binding Path=AcquisitionTimeChangedByInstrument, Converter={StaticResource BooleanToBrush}}"  Name="acquisitionTxtBox" TextChanged="onAcquisitionTimeChanged" >
    <TextBox.Text>
        <Binding Path="AcquisitionTime" Mode="TwoWay" StringFormat="{}{0:F6}" UpdateSourceTrigger="PropertyChanged" >
            <Binding.ValidationRules>
                <vm:AcquisitionTimeRule Min="200e-6" Max="40" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

背后的代码:

private void onAcquisitionTimeChanged(object sender, TextChangedEventArgs e)
{
    //acquisitionTxtBox.Foreground = Brushes.Black;
    ((ViewModel)Application.Current.Resources["vm"]).AcquisitionTimeChangedByInstrument = false;
}

AcquisitionTimeChangedByInstrument 是一个在 ViewModel 上引发 PropertyChanged 的​​属性。转换器会将颜色更改为黑色为假,蓝色为真。

  1. 在上面的表格中,它似乎按照描述的方式工作,但它似乎是一种奇怪的方式。如果我使用注释行直接更改颜色,绑定似乎会中断。也就是说,视图停止检查对 AcquisitionTimeChangedByInstrument 的更改。为什么?
  2. 这样做的正确方法是什么?

请记住,我只使用 WPF 几天;我还不了解高级功能。

编辑(按要求)

最后我会检查文本框中的值是否在 AcquisitionTime 中发生了变化。现在,我只是在单击按钮时设置 AcquisitionTimeChangedByInstrument=true 。这将发送 PropertyChanged 事件,但只有在我之前没有更改回调中的 acquireTxtBox.Foreground 时才会调用 get。

[ValueConversion(typeof(bool), typeof(SolidColorBrush))]
public class BooleanToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (null == value)
        {
            return null;
        }
        if (value is bool)
        {
            if ((bool)value)
            {
                return (SolidColorBrush)Brushes.DeepSkyBlue;
            }
            return (SolidColorBrush)Brushes.Black;
        }

        Type type = value.GetType();
        throw new InvalidOperationException("No type " + type.Name);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

【问题讨论】:

  • 改变前景色的条件是什么?您能否提供条件以及转换器代码,我将能够为您提供帮助。

标签: wpf textbox foreground


【解决方案1】:

在本地设置依赖属性可以优先于其他设置。实际上,您最终会覆盖绑定。使用

acquisitionTxtBox.SetCurrentValue(ForegroundProperty, Brushes.Black);

Blog entry explaining setcurrentvalue

【讨论】:

    猜你喜欢
    • 2013-01-29
    • 2013-01-15
    • 2011-04-27
    • 2018-08-08
    • 2018-04-14
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多