简体   繁体   English

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

[英]WPF How to display error message next to text box using INotifyDataErrorInfo

I am new to WPF and started following the tutorial below. 我是WPF的新手,并开始关注以下教程。

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

It is using error template to display the error like below 它正在使用错误模板来显示错误,如下所示

<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>

I got how to display the error message just below the text box as in the tutorial. 我得到了如何在本教程中的文本框下方显示错误消息。 However, I wanted to display the error message next to the text box instead of below the text box. 但是,我想在文本框旁边而不是文本框下方显示错误消息。

Is there a way to do it? 有办法吗? I tried to define a new grid column and tried to set the StackPanel to position at that new grid but it does not work. 我试图定义一个新的网格列,并试图将StackPanel设置在该新网格上,但是它不起作用。 (Grid.Column does not seems to be valid in there) (Grid.Column在其中似乎无效)

You need to adjust ErrorTemplate : 您需要调整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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM