2010-11-24 105 views
1

我在窗體上有一個組合框和按鈕。組合框包含類別。如果它們是基於布爾值的「系統類別」,我想允許/禁止未決。WPF/C#IDataErrorInfo Not Firing

這是我的XAML:

<Window.Resources> 
    <Style TargetType="{x:Type ComboBox}"> 
     <Style.Triggers> 
      <Trigger Property="Validation.HasError" Value="true"> 
       <Setter Property="ToolTip" 
       Value="{Binding RelativeSource={RelativeSource Self}, 
         Path=(Validation.Errors)[0].ErrorContent}"/> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 

這是兩個控件棧面板在其中:

   <StackPanel Grid.Column="1" Grid.Row="1"> 
        <Label Content="Delete Category" Height="28"/> 
        <ComboBox x:Name="comboBox_DeleteCategory" 
           Grid.Row="1" 
           Height="29"         
           ItemsSource="{Binding Path=CategorySelected.Items, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" 
           SelectedItem="{Binding Path=CategorySelected.SelectedItem ,ValidatesOnDataErrors=True, NotifyOnValidationError=true}" 
           DisplayMemberPath="Name"/> 
        <Button Content="Delete" Height="25" Margin="0,5,0,0" HorizontalAlignment="Right" Width="103.307" Command="{Binding DeleteCommand}"/> 
       </StackPanel> 

我試圖讓組合框來顯示工具提示,如果確定它是一個系統類別。

DeleteCommand工作正常,所以我沒有遇到問題,當我得到一個系統類別的命中被禁用的按鈕。

這是我的代碼,以顯示工具提示:

#region IDataErrorInfo Members 

public string Error { get; set; } 

public string this[string columnName] 
{ 
    get 
    { 
    Error = ""; 
    switch (columnName) 
    { 
     case "comboBox_DeleteCategory": 
     if (CategorySelected.SelectedItem != null && CategorySelected.SelectedItem.IsInternal) 
     { 
      Error = CategorySelected.SelectedItem.Name + " is an system category and cannot be deleted."; 
      break; 
     } 
     break; 

    } 

    return Error; 
    } 
} 

#endregion 

有什麼建議?

感謝,

Eroc

回答

3

的索引(公共字符串此[字符串COLUMNNAME])被調用,已由最新的綁定更新更改的屬性名稱。也就是說,篩選「comboBox_DeleteCategory」(控件名稱)在這裏沒有幫助。您必須篩選由控件綁定更新的屬性,並確定它是否處於預期狀態。您可以在索引器中放置一個斷點並查看columnName的值。更重要的是,WPF根本不使用錯誤屬性。因此,沒有必要設置它。一個簡單的例子:

public class Contact : IDataErrorInfo, INotifyPropertyChanged 
{ 
    private string firstName; 
    public string FirstName 
    { 
     // ... set/get with prop changed support 
    } 

    #region IDataErrorInfo Members 

    public string Error 
    { 
     // NOT USED BY WPF 
     get { throw new NotImplementedException(); } 
    } 

    public string this[string columnName] 
    { 
     get 
     { 
      // null or string.Empty won't raise a validation error. 
      string result = null; 

      if(columnName == "FirstName") 
      { 
       if (String.IsNullOrEmpty(FirstName)) 
        result = "A first name please..."; 
       else if (FirstName.Length < 5) 
        result = "More than 5 chars please..."; 
      } 

      return result; 
    } 
} 

#endregion 

}