如何使用C#在WPF中设置BitmapImage.CreateOptions

时间:2009-06-03 12:07:07

标签: c# wpf bitmapimage

BitmapImage bi = new BitmapImage(new Uri(@"D:\DSC_0865.png"));
bi.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
img1.Source = bi;

在上面的代码中,如果我尝试设置bi.CreateOptions,则不会接受它。它显示为无。请问您能提出解决方案吗?

2 个答案:

答案 0 :(得分:2)

尝试使用Begin / EndInit设置BitmapImage

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
bi.UriSource = new Uri(@"D:\DSC_0865.png")
bi.EndInit();
img1.Source = bi;

答案 1 :(得分:1)

MSDN documentation of the BitmapImage constructor you used  有一个简短的注释,声明使用此构造函数创建的BitmapImage对象会自动初始化。初始化后,属性更改将被忽略。“

因此,在调用构造函数后设置CreateOptions没有任何效果。实际上,BitmapImage是在构造函数中创建的,所以它有意义。您可能会争辩说属性设置器应该抛出InvalidOperationException。

您的问题的解决方案是使用另一个构造函数,例如正如MSDN documentation page for the CreateOptions property上的示例所示。