2012-11-01 65 views
0

我有一個DataGrid,因爲這樣以XML格式添加下面的代碼。現在,如何以編程方式訪問名爲Combo1ComboBox?我無法使用名稱Combo1正常訪問它。我希望能夠找回它的價值,或更改的ItemsSource等如何以編程方式訪問Datagrid中的ComboBox

<DataGrid x:Name="dgData" AutoGenerateColumns="False" Margin="133,94,23,116" Grid.Column="1" SelectionChanged="dgData_SelectionChanged"> 
     <DataGrid.Columns> 
      <DataGridTextColumn Binding="{Binding Subject}" Header="Subject" Width="*"/> 
      <DataGridTemplateColumn Header="Status" Width="100"> 
       <DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <ComboBox Name="Combo1" Height="22" ItemsSource="{StaticResource StatusList}" SelectedItem="{Binding Status}"/> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellTemplate> 
      </DataGridTemplateColumn> 
     </DataGrid.Columns> 
</DataGrid> 

回答

0

你應該能找到你需要在這裏。不過,我會說,這樣做是不是最好的做法...

http://blogs.msdn.com/b/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx

private childItem FindVisualChild<childItem>(DependencyObject obj) 
    where childItem : DependencyObject 
{ 
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) 
    { 
     DependencyObject child = VisualTreeHelper.GetChild(obj, i); 
     if (child != null && child is childItem) 
      return (childItem)child; 
     else 
     { 
      childItem childOfChild = FindVisualChild<childItem>(child); 
      if (childOfChild != null) 
       return childOfChild; 
     } 
    } 
    return null; 
} 
0

ü可以嘗試使用這樣的:

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T :  DependencyObject 
{ 
    if (depObj != null) 
    { 
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
     { 
      DependencyObject child = VisualTreeHelper.GetChild(depObj, i); 
      if (child != null && child is T) 
      { 
       yield return (T)child; 
      } 

      foreach (T childOfChild in FindVisualChildren<T>(child)) 
      { 
       yield return childOfChild; 
      } 
     } 
    } 
} 

但我建議ü閱讀有關MVVM模式的更多信息。

相關問題