How do I know when XAML bindings are evaluated?
-Is there a method / event I can hook into?
-Is there a way I can force these bindings to evaluate?
I have the following XAML with 3 Images which each have their source a separate way:
<Window...>
<Window.Resources>
<local:ImageSourceConverter x:Key="ImageSourceConverter" />
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image x:Name="NonBindingImage" Grid.Column="0" Source="C:\Temp\logo.jpg" />
<Image x:Name="XAMLBindingImage" Grid.Column="1" Source="{Binding Converter={StaticResource ImageSourceConverter}}" />
<Image x:Name="CodeBehindBindingImage" Grid.Column="2" />
</Grid>
</Window>
Here is the converter referenced in the XAML:
public class ImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = new FileStream(@"C:\Temp\logo.jpg", FileMode.Open, FileAccess.Read);
image.EndInit();
return image;
}
And here is the window code:
...
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
Binding binding = new Binding { Source = CodeBehindBindingImage, Converter = new ImageSourceConverter() };
BindingOperations.SetBinding(CodeBehindBindingImage, Image.SourceProperty, binding);
object xamlImageSource = XAMLBindingImage.Source; // This object will be null
object codeBehindImageSource = CodeBehindBindingImage.Source; // This object will have a value
// This pause allows WPF to evaluate XAMLBindingImage.Source and set its value
MessageBox.Show("");
object xamlImageSource2 = XAMLBindingImage.Source; // This object will now mysteriously have a value
}
}
...
When the binding is set via code using the same converter, it evaluates immediately.
When the binding is set via XAML and a converter, it defers evaluation to some later time. I randomly threw a call to MessageBox.Show in the code, and it seemed to cause the XAML binding source to evaluate.
Is there any way I can address this?
It will be evaluated on render. As MessageBox.Show() causes the UI thread to pump it will be evaluated before the messagebox is being shown.
Try hooking into the Loaded method of the WPF Window and running what you need to do there.
Edit: According to http://blogs.msdn.com/b/mikehillberg/archive/2006/09/19/loadedvsinitialized.aspx the loaded event should run after databinding. Failing that I would suggest looking at using the Dispatcher to queue up your code to run on the UI thread using Invoke