2014-10-16 88 views
1

我正在創建一個包含ContentPresenter的UserControl。我使用Datagrid將contentPresenter填充到窗口中,將itemsSource綁定到列表,但不起作用。在ContentPersenter中綁定ItemsSource Datagrid

我的Datagrid是空的。但是當我將DataGrid移出UserControl時,我得到了Inside數據。

我的用戶 XAML:

<UserControl Name="Instance" ...> 
    <Grid> 
     <ScrollViewer> 
      <ContentPresenter Content="{Binding Path=AdditionnalContent, ElementName=Instance}" /> 
     </ScrollViewer> 
    </Grid> 
</UserControl> 

C#:

public Object AdditionnalContent 
{ 
    get { return (object)GetValue(ContentProperty); } 
    set { SetValue(ContentProperty, value); } 
} 

public static readonly DependencyProperty AdditionnalContentProperty = DependencyProperty.Register("AdditionnalContent", typeof(object), typeof(MyUserControl), 
     new PropertyMetadata(null)); 

我的窗口

<Window Name="win" ...> 
    <Grid> 
     <my:MyUserControl> 
      <my:MyUserControl.AdditionnalContent> 
       <!-- Datagrid is empty --> 
       <DataGrid ItemsSource="{Binding LIST, ElementName=win}" AutoGenerateColumns="True" /> 
      </my:MyUserControl.AdditionnalContent> 
     </my:MyUserControl> 

     <!-- Datagrid have content --> 
     <DataGrid ItemsSource="{Binding LIST, ElementName=win}" AutoGenerateColumns="True" /> 
    </Grid> 
</Window> 

C#:

public partial class MainWindow : Window 
{ 
    public List<Object> LIST 
    { 
     get; 
     private set; 
    } 

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

感謝

+0

下載snoopwpf.codeplex.com。您可以使用此工具在應用程序運行時檢查UI,並發現綁定錯誤。 – 2014-10-16 19:13:27

+0

我在電腦上工作,我不是管理員,我不能安裝程序... – Northik 2014-10-16 19:36:38

回答

0

我解決我的問題與此代碼

<Window Name="win" ...> 
    <Grid> 
     <my:MyUserControl> 
      <my:MyUserControl.AdditionnalContent> 
       <DataGrid ItemsSource="{Binding LIST, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" /> 
      </my:MyUserControl.AdditionnalContent> 
     </my:MyUserControl> 
    </Grid> 
</Window> 

我解決不了現在答案,因爲我想了解的振振有辭的解釋。 我知道它會試圖找到父窗口控件的父窗口,但它已經在窗口中聲明,所以綁定爲什麼沒有看到由他的名字控制的窗口。

謝謝

0

你結合指向一個Window元素的屬性,它不知道它是什麼。它只知道的路徑是Window的屬性

假設您的LIST位於Window的DataContext之內。您必須明確指出WindowDataContext

<DataGrid ItemsSource="{Binding Path=DataContext.LIST, ElementName=win}" AutoGenerateColumns="True" /> 
+0

我嘗試你的代碼,但它不工作。我編輯我的問題以顯示窗口的C#代碼,希望它會有所幫助。 – Northik 2014-10-16 19:05:32

相關問題