2011-10-12 65 views
2

如何知道何時評估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綁定源進行評估。

有什麼辦法可以解決這個問題嗎?

+2

我覺得你並不需要「修理」它在UI線程上運行,因爲它不破。它在需要時而不是在此之前被評估。 –

+0

我修改了這個問題不是有爭議的,但是如果你A)將列索引1的寬度更改爲自動並且B)拋出對Measure/Arrange的調用,XAMLBindingImage.Source仍爲空。我的理解是Measure/Arrange需要元素的大小,然後才能正確地佈置(以及如何知道具有空源的Image的大小)。 – Michael

+0

爲了完整起見,在窗口構造函數中對this.UpdateLayout()的額外調用也不會加載圖像源。 – Michael

回答

2

它將在渲染上評估。由於MessageBox.Show()會導致UI線程進行抽取,因此將在顯示消息框之前對其進行評估。

嘗試掛鉤到WPF窗口的加載方法和運行,你需要做那裏。

編輯:根據http://blogs.msdn.com/b/mikehillberg/archive/2006/09/19/loadedvsinitialized.aspx加載的事件應該在數據綁定後運行。如果做不到這一點,我建議在尋找使用Dispatcher排隊你的代碼使用調用

+0

我試過這個:將代碼放入Loaded仍然會產生XAML中綁定集的空結果。我的困惑來源於爲什麼兩個綁定(代碼和XAML)行爲不同,當他們評估 – Michael

+0

我已經更新了我的帖子,包括另一種方法 –

+0

謝謝方面,打電話時您設置線程的優先級的DispatcherPriority Dispatcher.BeginInvoke工作.Loaded。但是,這仍然看起來很奇怪,因爲Measure()和Arrange()似乎清楚地表明他們將評估上面示例中基於轉換器的綁定。 – Michael