gpt4 book ai didi

c# - 何时评估 XAML 绑定(bind)?

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:05 26 4
gpt4 key购买 nike

我如何知道何时评估 XAML 绑定(bind)?

-是否有我可以 Hook 的方法/事件?

-有没有办法强制这些绑定(bind)进行评估?

我有以下带有 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
}
}
...

当使用同一转换器通过代码设置绑定(bind)时,它会立即求值。

当通过 XAML 和转换器设置绑定(bind)时,它会将评估推迟到以后的某个时间。我随机地在代码中调用了 MessageBox.Show,它似乎导致 XAML 绑定(bind)源求值。

有什么办法可以解决这个问题吗?

最佳答案

它将在渲染时被评估。由于 MessageBox.Show() 导致 UI 线程进行抽取,因此将在显示消息框之前对其进行评估。

尝试连接到 WPF 窗口的 Loaded 方法并在那里运行您需要执行的操作。

编辑:根据http://blogs.msdn.com/b/mikehillberg/archive/2006/09/19/loadedvsinitialized.aspx加载的事件应该在数据绑定(bind)之后运行。如果做不到这一点,我建议您考虑使用 Dispatcher使用 Invoke 排队您的代码以在 UI 线程上运行

关于c# - 何时评估 XAML 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7741844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com