2015-03-03 17 views
0

我的代碼如下獲取行值

MainWindow.Xaml

 <ListBox Width="400" Margin="10" x:Name="myListBox" 
     ItemsSource="{Binding Path=GridVal}" SelectedItem="{Binding CurrentItem}"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
        <Expander Header="Header1" IsExpanded="True"> 
         <StackPanel> 
          <DataGrid 
          x:Name="dataGrid" 
          AutoGenerateColumns="False" 
          ItemsSource="{Binding Path=GridVal}" 
          Height="250" Width="250" SelectedItem="{Binding CurrentItem}"/> 
        </StackPanel> 
       </Expander> 
     </DataTemplate> 
     </ListBox.ItemTemplate> 

MainWindow.Xaml

public object CurrentItem 
    { 
    get{return _item;} 
    set{_item=value;} 
    } 

它顯示它具有擴展和一個列表框Datagrid

我想在DataGrid中的當前選定行對此我無法得到這個point.I我得到的DataTemplate項目,而不是Datagrid的

+0

使用raiseonproperty更改或onpropertychange RaiseonPropertyChange(「CurrentItem」); @kyle – 2015-03-03 13:46:08

+1

看來你已經綁定了'CurrentItem'列表和'DataGrid'。你確定你正在檢查正確的'CurrentItem'嗎?它應該是在類中也有'GridVal'屬性的一個 – Default 2015-03-03 13:54:16

+1

您是否在調試輸出中看到任何綁定錯誤?你可以展示你的viewmodels,你用作datacontexts嗎? – Default 2015-03-03 14:01:51

回答

1

您使用了錯誤的屬性來將數據綁定到您的CurrentItem屬性。取而代之的SelectedIndex,你應該將數據綁定到DataGrid.SelectedItem property

<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" 
    ItemsSource="{Binding GridVal}" Height="250" Width="250" 
    SelectedItem="{Binding CurrentItem}" /> 

雖然,作爲@default提到的,你也嘗試將數據綁定CurrentItem屬性爲兩個不同的控制特性,所以你需要添加一個不同的財產,以使其正常工作。此外,CurrentItem屬性應該與GridVal集合中的項目屬於同一類型。


UPDATE >>>

你似乎缺少一些信息,你也試圖將數據綁定同一集合到ListBox.ItemsSourceDataGrid.ItemsSource這是不可能的。 DataTemplate中的所有內容都將自動將其DataContext設置爲上述集合中的項目,例如。渲染時,每個數據項將在DataTemplate中設置爲DataContext

因此,對於您當前的代碼工作,該集合中的數據項應具有CurrentItemGridVal屬性,但我猜測他們不這樣做。在Visual Studio的輸出窗口中也應該有錯誤,清楚地告訴你在集合中的任何對象類型都不存在CurrentItem屬性。

我建議您閱讀MSDN上的Data Templating Overview‎頁面以幫助您更好地瞭解情況。

+0

雖然第二個'CurrentItem'包含在'DataTemplate'中,所以至少它們沒有綁定到相同的'DataContext'(除非在代碼示例之外的地方修改了它)。然而,他的解釋似乎指出他正在檢查「父母」財產,而不是兒童財產。 – Default 2015-03-03 14:01:33

+0

@默認,同意。 – Sheridan 2015-03-03 14:07:22

+0

@Sheridan你能用例子來解釋嗎? – Rohit 2015-03-03 14:08:56

0

您可以使用綁定與Relative source

{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}} 

或用指定的元素名稱:

{Binding Path=DataContext.PathToProperty, ElementName=myListBox}