【发布时间】:2011-10-12 14:39:07
【问题描述】:
我如何知道 XAML 绑定何时被评估?
-有没有我可以挂钩的方法/事件?
-有没有办法强制这些绑定进行评估?
我有以下 XAML,其中包含 3 个图像,每个图像都有不同的来源:
<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
}
}
...
当使用相同转换器通过代码设置绑定时,它会立即计算。
当通过 XAML 和转换器设置绑定时,它会将评估推迟到稍后的时间。我在代码中随机调用 MessageBox.Show,它似乎导致 XAML 绑定源进行评估。
有什么办法可以解决这个问题吗?
【问题讨论】:
-
我认为您不需要“修复”它,因为它没有损坏。它在需要时而不是之前进行评估。
-
我将问题修改为没有争议,但如果您 A) 将列索引 1 的宽度更改为自动并且 B) 调用 Measure/Arrange,XAMLBindingImage.Source 仍然为空。我的理解是 Measure/Arrange 需要元素的大小才能正确布局(以及如何知道带有 null 源的 am Image 的大小)。
-
为了完整起见,在窗口的构造函数中额外调用 this.UpdateLayout() 也不会加载图像源。