我知道如何在寫作時讓文字消失:我們應該使用GotFocus LostFocus. 對于我這樣做的例子TextBox:
<TextBox x:Name="SearchNotes" Foreground="Gray"
Text="Search" LostFocus="NoteBox_OnLostFocus"
GotFocus="NoteBox_GotFocus" BorderThickness="0"
Background="WhiteSmoke" TextChanged="TextBox_TextChanged"
Width="771"
/>
這是代碼:
public void NoteBox_GotFocus(object sender, RoutedEventArgs e)
{
SearchNotes.Text = "";
SearchNotes.Foreground = Brushes.White;
}
public void NoteBox_OnLostFocus(object sender, RoutedEventArgs e)
{
SearchNotes.Text = "Search";
SearchNotes.Foreground = Brushes.Gray;
}
現在,我正在嘗試對另一個做同樣的事情TextBox,但問題是它TextBox在Window模板中,所以我無法TextBox從代碼中訪問它(或者我不知道如何訪問它)
這是 XAML 代碼:
<TextBox x:Name="WindowTextbox" GotFocus="WindowTextbox_GotFocus" LostFocus="WindowTextbox_LostFocus" Text="Type..." TextChanged="WindowTextbox_TextChanged" FontSize="15" Foreground="White" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True" Background="#404040" BorderThickness="0" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Grid.RowSpan="3" Margin="0 0 0 23">
</TextBox>
當我試圖從代碼中訪問它時,我不能:

所以我想知道如何處理這個問題。
uj5u.com熱心網友回復:
這就是sender引數的用途,請參閱Routed Events Overview。
呼叫處理程式的物件是
sender引數報告的物件。
private void WindowTextbox_GotFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox)sender;
textBox.Text = "";
textBox.Foreground = Brushes.White;
}
private void WindowTextbox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox)sender;
textBox.Text = "Search";
textBox.Foreground = Brushes.Gray;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443434.html
上一篇:如何使用父按鈕的屬性使CommandParameter為ContextMenu中的MenuItem作業?
下一篇:除錯器顯示引發例外的屬性
