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

标签 c# wpf xaml binding

我如何知道何时评估 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/

相关文章:

c# - 访问类中的模拟 Request.ServerVariables

c# - 如何在绑定(bind)的 DataGrid 中编辑未绑定(bind)的单元格?

c# - WPF - ListView 中的 TextBlock 未水平对齐

c# - DataRow 中的 DataColumn 名称(不是 DataTable)

c# - WPF INotifyPropertyChanged 是如何工作的?

WPF 将 ContextMenu 绑定(bind)到 VM 中的 ContextMenu 属性

c# - 泛型类型转换器 - 泛型问题

c# - 如何成功实现WPF文本框验证?

c# - 如何使用 DisplayMemberPath 显示特定列中的项目

c# - pinvoke c 函数 - System.BadImageFormatException