![](/img/trans.png)
[英]C# Validate Date Picker in WPF using IDataErrorInfo & INotify
[英]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
使用最新綁定更新已更改的屬性名稱調用索引器( 公共字符串this [string columnName] )。 也就是說,過濾“ comboBox_DeleteCategory”(控件名稱)在這里無濟於事。 您必須篩選由控件的綁定更新的屬性,並確定它是否處於預期狀態。 您可以在索引器中放置一個斷點,並觀察columnName的值。 而且,WPF根本不使用Error屬性。 因此,沒有必要進行設置。 一個簡單的例子:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.