2016-07-29 77 views
-3

我有一個包含用戶控件C#WPF應用程序:錯誤:「此操作只適用於具有此模板應用於元素」

<UserControl 
     x:Name="payrollEntryControl" 
     x:Class="MyNamespace.PayrollEntryControl" 
     [...] 
     > 
    [...] 
</UserControl> 

在用戶控制,我有一個Telerik的RadDataForm

<telerik:RadDataForm 
     x:Name="payrollAddForm" 
     CurrentItem="[...]" 
     EditTemplate="{StaticResource myEditTemplate}" 
     /> 

該模板包含一個Telerik的RadGridViewButton

<telerik:RadGridView Grid.Row="0" Grid.Column="0" 
     x:Name="workGridView" 
     [...] 
     ItemsSource="{Binding [...]}" 
     > 
    <telerik:RadGridView.Columns> 
     [...] 
    </telerik:RadGridView.Columns> 
</telerik:RadGridView> 
<Button Grid.Row="1" Grid.Column="0" 
     Command="{Binding addWorkCommand, ElementName=payrollEntryControl}" 
     > 
    Add 
</Button> 

我想要的命令是,致電BeginInsert()。但我似乎無法訪問workGridView

我的命令,到目前爲止:

private DelegateCommand addWorkCommand_ = null; 
public DelegateCommand addWorkCommand 
{ 
    get 
    { 
     if (this.addWorkCommand_ == null) 
     { 
      this.addWorkCommand_ = new DelegateCommand(
       o => addWork(o) 
      ); 
     } 

     return this.addWorkCommand_; 
    } 
} 

private void addWork(object o) 
{ 
    var addForm = this.payrollAddForm; 
    var editTemplate = addForm.EditTemplate; 
    var workGrid = editTemplate.FindName("workGridView", addForm); 
} 

我的問題?當我打這個電話給editTemplate.FindName(),我得到一個異常:

This operation is valid only on elements that have this template applied.

我不明白。我從表單中獲取模板。它如何不能被應用?

+0

這個問題似乎是非常具體的Telerik的庫。您可能需要專門從熟悉該供應商產品的人那裏獲得幫助。除此之外,如果沒有好的[mcve],任何人都可能很難直接診斷問題。請解釋您已經嘗試過的有關調試和研究錯誤消息的內容(包括[在此處]返回的項目的相關性(https://stackoverflow.com/search?q=%5Bc%23%5D+%22This+操作是+有效+只+上+元素+ +那個具有+ +這個模板+施用。%22))。 –

回答

0

彼得Duniho的評論指出我this答案,這解決了我的問題。

This method will help you:

public T FindElementByName<T>(FrameworkElement element, string sChildName) where T : FrameworkElement 
{ 
    T childElement = null; 
    var nChildCount = VisualTreeHelper.GetChildrenCount(element); 
    for (int i = 0; i < nChildCount; i++) 
    { 
     FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement; 

     if (child == null) 
      continue; 

     if (child is T && child.Name.Equals(sChildName)) 
     { 
      childElement = (T)child; 
      break; 
     } 

     childElement = FindElementByName<T>(child, sChildName); 

     if (childElement != null) 
      break; 
    } 

    return childElement; 
} 

And, how I use it, just add button, and on button Click:

private void Button_OnClick(object sender, RoutedEventArgs e) 
{ 
    var element = FindElementByName<ComboBox>(ccBloodGroup, "cbBloodGroup"); 
} 
[1]: https://stackoverflow.com/a/19907800/243563 

另一種方法是通過workGridView作爲CommandParameter:

<Button Grid.Row="1" Grid.Column="0" 
    CommandParameter="{Binding ElementName=workGridView}" 
    Command="{Binding addWorkCommand}" > 
.... 

private void addWork(object o) 
{ 
    RadGridView grid = o as RadGridView; 
    grid.BeginInsert(); 
} 
相關問題