2014-10-03 90 views
0

試圖理解數據綁定,這完全看起來像是一個菜鳥的錯誤,但我不知道爲什麼會發生。InitializeComponent在綁定時觸發StackOverflow異常

CS

namespace MuhProgram 
{ 
    public partial class MainWindow : Window 
    { 
     public string foobar 
     { 
      get { return "loremipsum"; } 
     } 

     public MainWindow() 
     { 
      InitializeComponent(); 
     } 
    } 
} 

XAML:在MainWindow()法StackOverflowException InitializeComponent()電話

<Window x:Class="MuhProgram.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:MuhProgram" 
     Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
     <local:MainWindow x:Key="classMainWindow"/> 
    </Window.Resources> 

    <Grid> 
     <Label Content="{Binding Source={StaticResource classMainWindow}, Path=foobar}"></Label> 
    </Grid> 
</Window> 

調試點。

我也嘗試在網格中設置DataContext屬性爲"{StaticResource classMainWindow}",但效果是一樣的。

回答

2

StackOverflow上引發異常,因爲你是在遞歸此行

<local:MainWindow x:Key="classMainWindow"/> 

創建主窗口的實例時的InitializeComponent()被調用,則初始化XAML和編譯BAML加載它。在加載它時發現Label內容需要MainWindow的另一個實例來綁定它的Content DP。因此,它會遞歸地創建MainWindow,直到它與SO異常崩潰。


您不需要聲明MainWindow的另一個實例。綁定標籤到父實例是這樣的:

<Label Content="{Binding Path=foobar, RelativeSource={RelativeSource FindAncestor, 
                  AncestorType=Window}}"/> 

OR

要麼設置的DataContext本身,讓標籤從父窗口繼承它。

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
    .... 
    <Label Content="{Binding foobar}"/> 

OR

集合X:名稱在窗口和使用的ElementName綁定。

<Window x:Name="myWindow"> 
    ..... 
    <Label Content="{Binding foobar, ElementName=myWindow}" /> 
+0

你是什麼意思「聲明MainWindow的另一個實例」?我在哪裏做? – 2014-10-03 08:14:47

+1

這裏你聲明另一個實例''。 – 2014-10-03 08:15:23

+0

這就是爲什麼我得到堆棧溢出?這個人[這裏](http://msdn.microsoft.com/en-us/library/ms752347(v = vs.110).aspx)正在做同樣的事情(第一個XAML代碼片段)。 – 2014-10-03 08:19:31