2013-10-04 39 views
0

我想添加一個背景圖像到一個文本框,但在textChange事件,圖像消失如預期,但如果我退格或刪除文本中的文本,使它是空的,我拿到了DirectoryNotFoundException被處死。 和目錄:WPF目錄未找到異常和PresentationCore.pdb未加載

無法找到部分路徑'C:\ myProjectFolder \ bin \ Debug..img \ txtBackground.png'。

的XAML:

<TextBox Name="myTextBox" Width="200" TextChanged="myTextBox_TextChanged"> 

<TextBox.Background> 
<ImageBrush ImageSource="img/txtBackground.png" /> 
</TextBox.Background> 

C#代碼:

private void myTextBox_TextChanged(object sender, TextChangedEventArgs e) 
{ 
if (myTextBox.Text == "") 
{ 
ImageBrush textImageBrush = new ImageBrush(); 
textImageBrush.ImageSource = 
new BitmapImage(
    new Uri(@"..img/txtBackground.png", UriKind.Relative) 
); 
myTextBox.Background = textImageBrush;  
} 
else 
{ 
myTextBox.Background = null; 
} 
} 

刪除引用,重新添加它們,建立/清潔解決方案和重建,但沒有。 只有當我嘗試將背景添加到文本框時,纔會出現這些錯誤。

+0

有圖像的img文件夾,它是Debug文件夾嗎? – Nitin

+0

是的,我將img文件夾添加到Debug文件夾。 – Asynchronous

+0

理想情況下,您應該將img文件夾添加到您的項目中,並將圖像添加到BuildAction中作爲資源 – Nitin

回答

1

假設有圖像的IMG文件夾是項目下(下不了debug文件夾中,理想情況不應該在Debug文件夾)和圖像的BuildAction的設置爲資源,你可以試試這個:

new BitmapImage(new Uri("pack://application:,,,/img/txtBackground.png", UriKind.Absolute)); 

如果你在Debug文件夾都的img那麼你必須達到高達該

new Uri(@"bin/Debug/img/txtBackground.png", UriKind.Relative) 
+0

其實這個工作:但我改變了上面的這個: 新的BitmapImage(Uri uri = new Uri(「pack:// application:,,,/img/txtBackground.png」,UriKind.Absolute)); 對此: new BitmapImage(new Uri(「pack:// application:,,,/img/txtBackground.png」,UriKind.Absolute)); – Asynchronous

+0

yup ..只寫了這裏的代碼..所以沒有看到;) – Nitin

+0

非常感謝:圖像不在調試文件夾中,我刪除它,它在項目文件夾下。構建操作設置爲:資源。非常感謝:這是一個痛苦。 – Asynchronous

0

你烏里應該讀

new Uri(@"/img/txtBackground.png", UriKind.Relative) 

至少這是錯誤信息說什麼。

+0

我試過了,但仍然出現錯誤:項目中引用了其他圖像:../img/imagename和它們工作正常。 – Asynchronous

+0

那麼你錯過了你的路徑中的斜線?看看你提供的uri,它會顯示「..img」,而不是「../img」 – nvoigt

+0

我已經儘可能以各種方式嘗試過了:../img/image或img/or/img,我仍然收到錯誤。 – Asynchronous

0

你也可以試試這個:

textImageBrush.ImageSource =new BitmapImage("/Projectname;Component/img/txtBackground.png"); 

圖片的Build Action必須設置爲Resource