文本框失去焦点后更改文本颜色

时间:2015-07-25 09:36:37

标签: c# wpf mvvm textbox textcolor

我希望在将项目添加到列表后将文本框默认文本颜色更改为原始默认颜色。

XAML

<TextBox Name="AddLocationTextBox" Text="{Binding Path=AddLocationName, UpdateSourceTrigger=PropertyChanged}" 
         LostFocus="AddLocationTextBox_LostFocus" GotFocus="AddLocationTextBox_GotFocus" HorizontalAlignment="Left" Height="23" Margin="10,37,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="285">                    

        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{Binding AddLocationCommand}" />
        </TextBox.InputBindings>
</TextBox>

View中的代码

public LocationManagerView()
{
    InitializeComponent();

    AddLocationTextBox.Foreground = Brushes.Gray;   
}

private void AddLocationTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    AddLocationTextBox.Text = string.Empty;
    AddLocationTextBox.Foreground = Brushes.Black;
}

private void AddLocationTextBox_LostFocus(object sender, RoutedEventArgs e)           
{
    AddLocationTextBox.Foreground = Brushes.Gray;
}

视图模型

public RelayCommand AddLocationCommand { get; private set; }
private void AddLocation()
{
    if ( AddLocationName != null)
    {
        Locations.Add(new Location()
        {
            Name = AddLocationName,
        });
        AddLocationName = "Enter New Location";
        Keyboard.ClearFocus();

        ////change textcolor to gray////
    }
    else
    {
        return;
    }     
}

将AddLocationName再次设置为&#34;输入新位置&#34;我想将textcolor更改为灰色。 看起来Keyboard.ClearFocus()没有在视图中调用LostFocus方法。

任何想法我如何使这项工作?

1 个答案:

答案 0 :(得分:1)

如果您只想将TextBox的前景更改为灰色,而不是强迫AddLocationTextBox失去焦点,则应手动更改前景(即使用AddLocationTextBox.Foreground = Brushes.Gray而不是Keyboard.ClearFocus())。

如果您正在寻找一种方法来强制当前关注的元素失去焦点,那么您可以使用下面的代码而不是Keyboard.ClearFocus()

UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));