WPF如何使用INotifyDataErrorInfo在文本框旁边显示错误消息

本文关键字:显示 错误 消息 文本 何使用 INotifyDataErrorInfo WPF | 更新日期: 2023-09-27 18:22:03

我是WPF的新手,开始学习下面的教程。

http://social.technet.microsoft.com/wiki/contents/articles/19490.validating-data-in-wpf-4-5-using-the-inotifyerrordataerror-interface.aspx#Visual_feedback

它使用错误模板来显示错误,如下

<Validation.ErrorTemplate>
    <ControlTemplate>
        <StackPanel>
            <!-- Placeholder for the TextBox itself -->
            <AdornedElementPlaceholder x:Name="textBox"/>
            <ItemsControl ItemsSource="{Binding}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding ErrorContent}" Foreground="Red"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </ControlTemplate>
</Validation.ErrorTemplate>

我了解了如何像教程中那样在文本框下方显示错误消息。但是,我想在文本框旁边显示错误消息,而不是在文本框下面。

有办法做到吗?我试图定义一个新的网格列,并试图将StackPanel设置在该新网格的位置,但它不起作用。(Grid.Column在那里似乎无效)

WPF如何使用INotifyDataErrorInfo在文本框旁边显示错误消息

您需要调整ErrorTemplate:

<TextBox Text="{Binding Username, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}">
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <!-- Align text box and error list horizontally -->
            <StackPanel Orientation="Horizontal">
                <AdornedElementPlaceholder x:Name="textBox"/>
                <ItemsControl ItemsSource="{Binding}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding ErrorContent}" Foreground="Red"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
</TextBox>