我得到了InvalidOperationException
。此代码在一个线程中运行。我已将其委托给UI线程来处理UI。问题是由于我的资源而发生的吗?
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/LiarDice;component/" + imagePath);
logo.EndInit();
currentGuessDice.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate()
{
currentGuessDice.Source = logo;
}));
我略微改变了我的代码,现在错误变为:
Part URI cannot end with a forward slash.
新守则:
currentGuessDice.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate()
{
BitmapImage logo = new BitmapImage();
logo.BeginInit();
logo.UriSource = new Uri("pack://application:,,,/LiarDice;component/" + imagePath);
logo.EndInit();
currentGuessDice.Source = logo;
}));
答案 0 :(得分:0)
除了您的imagePath
变量my null
之外,原始代码中的问题是您在UI线程以外的线程中创建一个BitmapImage,然后在UI线程中使用。
为了使其正常工作,您必须冻结BitmapImage:
var logo = new BitmapImage(
new Uri("pack://application:,,,/LiarDice;component/" + imagePath));
logo.Freeze(); // here
currentGuessDice.Dispatcher.Invoke(new Action(() => currentGuessDice.Source = logo));