我有 3 個文本框,用戶可以修改它們以更改視窗某些顏色的 RGB 顏色。我正在做的給他們一個可視化是在所述文本框旁邊有一個框,顯示他們在文本框中用所述 RGB 值制作的顏色。為此,我將所有 3 個文本框的 TextChanged 事件設定為一個方法,該方法從 3 個文本框中獲取文本,使用 TryParse 將它們轉換為整數,將數字分配給畫筆,然后將畫筆分配給框,以便用戶可以看到。XAML 看起來像這樣:
<TextBox Name="ColorPickerDisplayRed" Background="Transparent"
BorderBrush="Transparent"
FontFamily="Moon 2.0"
Foreground="#6BAAFF"
Text="255"
TextAlignment="Center"
Margin="0, -1.2, 0, 0"
TextChanged="UpdateColorPickerDisplay"/>
我復制并粘貼了綠色和藍色,所以除了文本框的名稱外,一切都相同。然后,為了獲得整數值,我有這個:
private void UpdateColorPickerDisplay(object sender, TextChangedEventArgs e)
{
int R;
int G;
int B;
if (int.TryParse(ColorPickerDisplayRed.Text, out R)) ;
if (int.TryParse(ColorPickerDisplayGreen.Text, out G)) ;
if (int.TryParse(ColorPickerDisplayBlue.Text, out B)) ;
var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));
ColorPickerDisplay.Background = brush;
}
但是當我運行它時,我收到一條錯誤訊息,指出“ColorPickerDisplayGreen 為空。”。然后我嘗試將每個框的文本設定為測驗并得到相同的錯誤。我對所有 3 個文本框都試過了,它只對紅色有效。是不是因為我從所有 3 個文本框中呼叫了相同的方法?
解決了,不知道 TextChanged 被立即呼叫了。
uj5u.com熱心網友回復:
添加 ?在訪問 Text 屬性之前,它將解決該問題
int R;
int G;
int B;
if (int.TryParse(ColorPickerDisplayRed?.Text, out R)) ;
if (int.TryParse(ColorPickerDisplayGreen1?.Text, out G)) ;
if (int.TryParse(ColorPickerDisplayBlue?.Text, out B)) ;
var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));
ColorPickerDisplayRed.Background = brush;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313946.html
