2013-04-01 43 views
0

下面是我正在使用的示例代碼。我爲TextBox創建了附加屬性,名爲ErrorMessageServce.ErrorMessage。無論何時填入ValidationError,它都會調用ErrorMessageService的財產變更事件。如何從其模板字段獲取datagrid單元格對象wpf

從那裏我想要的是,如果出現錯誤,我想突出顯示特定的單元格。所以我想在ErrorMessageServicePropertyChanged做,但是我得到了TextBox對象。

所以問題是:

1)如何從文本框對象獲得Datagridcell;

或:

2)如何照亮特定的細胞;

3)如何顯示在編輯模式下該特定小區(即..應顯示文本框)

XAML:

<DataGridTemplateColumn> 
    <DataGridTemplateColumn.CellTemplate> 
     <DataTemplate> 
      <TextBlock Grid.Column="1" 
       Width="150" Height="25"> 
      </TextBlock> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellTemplate> 

    <DataGridTemplateColumn.CellEditingTemplate> 
     <DataTemplate> 
      <TextBox Grid.Column="1" Style="{DynamicResource ValidatingTextBox}" 
       x:Name="NameText" Text="{Binding CompanyName,ValidatesOnDataErrors=True,ValidatesOnExceptions=True}" App:ErrorMessageService.ErrorMessage="{Binding ValidationResult,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="150" Height="25"> 
      </TextBox> 
     </DataTemplate> 
    </DataGridTemplateColumn.CellEditingTemplate> 
</DataGridTemplateColumn> 

ErrorMessageService

public static class ErrorMessageService 
{  
    public static readonly DependencyProperty ValidationErrorProperty = 
     DependencyProperty.RegisterAttached("ErrorMessage", typeof(ValidationResult), typeof(ErrorMessageService), 
     new FrameworkPropertyMetadata(default(ValidationResult), ErrorMessageServicePropertyChanged)); 

    public static ValidationResult GetErrorMessage(Control control) 
    { 
     return (ValidationResult)control.GetValue(ValidationErrorProperty); 
    } 

    public static void SetErrorMessage(Control control, object value) 
    { 
     control.SetValue(ValidationErrorProperty, value); 
    }  

    private static void ErrorMessageServicePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     //here i am getting d as textbox , from this how to get datagridcell object , so that i can highlight 
    } 
} 

感謝。

回答

1

我已經嘗試了下面,它工作正常,從單元格編輯模板中的文本框中獲取Datagridcell對象。我想它可以幫助someothers太

public static T FindAncestor<T>(DependencyObject dependencyObject) 
     where T : class 
    { 
     DependencyObject target = dependencyObject; 
     do 
     { 
      target = VisualTreeHelper.GetParent(target); 
     } 
     while (target != null && !(target is T)); 
     return target as T; 
     } 

得到DatagridCellobject後,它具有類似於IsEdit性質,使得真正的使得該細胞可編輯

感謝

相關問題