如何知道何時評估XAML綁定?何時評估XAML綁定?
-Is有一個方法/事件我可以掛接到?
-Is有什麼辦法可以強制這些綁定的評價?
我有3個圖像它們都有各自的源獨立的方式,下面的XAML:
<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>
這裏是在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;
}
這裏是窗口代碼:
...
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
}
}
...
當通過使用相同轉換器的代碼設置綁定時,它會評估immedi ately。
當結合是通過XAML和轉換器設置,它推遲評價稍後時間。我隨機向代碼中的MessageBox.Show發出一個調用,並且它似乎導致XAML綁定源進行評估。
有什麼辦法可以解決這個問題嗎?
我覺得你並不需要「修理」它在UI線程上運行,因爲它不破。它在需要時而不是在此之前被評估。 –
我修改了這個問題不是有爭議的,但是如果你A)將列索引1的寬度更改爲自動並且B)拋出對Measure/Arrange的調用,XAMLBindingImage.Source仍爲空。我的理解是Measure/Arrange需要元素的大小,然後才能正確地佈置(以及如何知道具有空源的Image的大小)。 – Michael
爲了完整起見,在窗口構造函數中對this.UpdateLayout()的額外調用也不會加載圖像源。 – Michael