在事件上更改WPF文本框前景颜色

时间:2014-04-07 04:05:21

标签: wpf textbox foreground

我想根据传入的事件更改文本框的前景色(传入的数字与文本框中的不同),但如果通过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. 这样做的正确方法是什么?
  3. 请记住,我只使用WPF几天;我还不了解高级功能。

    编辑(按要求)

    最后,我将检查在AcquisitionTime中文本框中的值是否已更改。现在,我只是在单击按钮时设置AcquisitionTimeChangedByInstrument = true。这将发送PropertyChanged事件,但只有在我之前没有在回调中更改acquisitionTxtBox.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();
        }
    }
    

1 个答案:

答案 0 :(得分:3)

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

acquisitionTxtBox.SetCurrentValue(ForegroundProperty, Brushes.Black);

Blog entry explaining setcurrentvalue