在我的 WPF 應用程式中,我有以下資源:
<ResourceDictionary>
<Style x:Key="OnErrorTextBoxStyle" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<StackPanel>
<AdornedElementPlaceholder x:Name="placeholder" />
<TextBlock FontSize="11" FontStyle="Italic" Foreground="Red"
Text="{Binding ElementName=placeholder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
我的文本框:
<TextBox Grid.Column="0"
Grid.Row="1"
Style="{StaticResource one rrorTextBoxStyle}"
Height="30"
Margin="5,8,8,15">
<TextBox.Text>
<Binding Path="MyPath"
UpdateSourceTrigger="PropertyChanged"
>
<Binding.ValidationRules>
<Rules:PathValidationRule ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
在視圖模型中,我的 myPath 屬性具有以下方面(我在這里只顯示重要的東西):
public string MyPath
{
get => myObject.currentPath.LocalPath; // currentPath is an Uri Object
set
{
if (!string.IsNullOrWhiteSpace(value))
{
// creates an Uri object using value and Uri.TryCreate
if (Uri.TryCreate(value, UriKind.Absolute, out Uri newUri))
{
myObject.currentPath = newUri;
OnPropertyChanged();
}
}
}
}
當我嘗試從視圖模型設定 MyPath 屬性時,出現以下錯誤:
Cannot get 'Item[]' value (type 'ValidationError') from
'(Validation.Errors)' (type 'ReadOnlyObservableCollection`1').
BindingExpression:Path=AdornedElement.(0)[0].ErrorContent;
DataItem='AdornedElementPlaceholder' (Name='placeholder'); target
element is 'TextBlock' (Name=''); target property is 'Text' (type
'String')
ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException:
Specified argument was out of the range of valid values. Parameter
name: index'
如果我從 TextBox 中洗掉靜態資源 Style="{StaticResource one rrorTextBoxStyle}",則一切正常。所以我想我在靜態資源中做錯了什么,但我不知道是什么。
我的 TextBox 有一個驗證規則,用于驗證用戶輸入的內容。我沒有使用任何其他驗證機制,例如 INotifyDataErrorInfo 和 IDataErrorInfo。
uj5u.com熱心網友回復:
試試這個系結ControlTemplate:
<TextBlock FontSize="11" FontStyle="Italic" Foreground="Red"
Text="{Binding [0].ErrorContent}" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429090.html
