0

DataGrid在 XML 中添加了如下代码。现在,我如何以编程方式访问ComboBox命名?Combo1我无法使用 name 正常访问它Combo1。我希望能够检索它的值,或更改 itemssource 等。

<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>
4

2 回答 2

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;
}
于 2012-11-01T20:07:15.160 回答
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 模式的信息。

于 2012-11-01T20:10:18.260 回答