C# WPF 绑定、ValidationRule 和默认值

发布于 2024-10-25 19:01:38 字数 2391 浏览 1 评论 0原文

我是 WPF 和 C# 新手,我的应用程序有问题。我有一个文本框,我想在其中添加 ValidationRule 来验证文本。现在我想在文本框中有一个默认值,但我不知道该怎么做。我尝试了很多方法,但在谷歌搜索问题时发现的提示似乎根本不起作用。

还有什么方法可以在不使用 ProjectData 类文件的情况下执行此操作?对我来说,必须创建一个只有一个值的类才能实现验证似乎很奇怪。

我的 ValidationRule 看起来像这样:

public class OpcValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string source = (string)value;
            if(!source.StartsWith("Test")) 
            {
                return new ValidationResult(false, msg);
            }


            // Valid!!!!
            return new ValidationResult(true, null);
        }
    }

我的 TextBox 看起来像这样:

<TextBox x:Name="OPCAddressBox" Style="{StaticResource textBoxInError}" HorizontalAlignment="Right" TextWrapping="NoWrap" VerticalAlignment="Top" Margin="0,10,8,0" Width="150">
                    <TextBox.Text>
                        <Binding Path="OpcServerAddress" Source="{StaticResource pdd}" UpdateSourceTrigger="PropertyChanged">
                            <Binding.ValidationRules>
                                <local:OpcValidationRule />
                            </Binding.ValidationRules>
                        </Binding>
                    </TextBox.Text>
                </TextBox>

我的资源看起来像这样:

<Window.Resources>
        <local:ProjectData Height="1000" Width="1000" OpcServerAddress="opc.tcp://address:port" x:Key="pdd"/>

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

我的 ProjectData 文件看起来像这样:

public class ProjectData
    {
        private string opcServerAddress;
        public string OpcServerAddress
        {
            get { return opcServerAddress; }
            set { opcServerAddress = value; }
        }

        public ProjectData()
        {
        }
    }

I new to WPF and C# and I have a problem with my application. I have a TextBox which I want to have a ValidationRule on to validate the text. Now I want to have a default value in the TextBox but i can't figure out how to do it. I've tried alot of ways and the tips I find when googling the problem doesn't seem to work at all.

Also is there any way to do this without the use of an ProjectData class file? To me it seems wierd to have to make a class with just one value to be able to achieve validation.

My ValidationRule looks like this:

public class OpcValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string source = (string)value;
            if(!source.StartsWith("Test")) 
            {
                return new ValidationResult(false, msg);
            }


            // Valid!!!!
            return new ValidationResult(true, null);
        }
    }

My TextBox looks like this:

<TextBox x:Name="OPCAddressBox" Style="{StaticResource textBoxInError}" HorizontalAlignment="Right" TextWrapping="NoWrap" VerticalAlignment="Top" Margin="0,10,8,0" Width="150">
                    <TextBox.Text>
                        <Binding Path="OpcServerAddress" Source="{StaticResource pdd}" UpdateSourceTrigger="PropertyChanged">
                            <Binding.ValidationRules>
                                <local:OpcValidationRule />
                            </Binding.ValidationRules>
                        </Binding>
                    </TextBox.Text>
                </TextBox>

My Resources looks like this:

<Window.Resources>
        <local:ProjectData Height="1000" Width="1000" OpcServerAddress="opc.tcp://address:port" x:Key="pdd"/>

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

My ProjectData file looks like this:

public class ProjectData
    {
        private string opcServerAddress;
        public string OpcServerAddress
        {
            get { return opcServerAddress; }
            set { opcServerAddress = value; }
        }

        public ProjectData()
        {
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鯉魚旗 2024-11-01 19:01:38

您必须知道,通常,如果您想以“正确”的方式实现 WPF 应用程序,您的 XAML 将绑定到 ViewModel,并保留属性。
我知道对于您必须保留在这里的少量财产来说,这似乎有点沉重,但相信我,当您拥有更大的用户界面时,它会很棒。
您还可以查看触发器,它可以帮助您在不添加类的情况下验证某些内容(但如果您有很多字段需要验证,则会非常繁重)
如果您还没有阅读过这篇文章,我建议您查看这篇文章,它确实帮助我了解了有关 WPF 中的验证的更多信息:

http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

编辑

对于默认值:

您的项目数据类必须实现接口“INotifyPropertyChanged”
这允许在每次更改文本时触发一个事件,从而更新绑定。完成此操作后(我鼓励您使用 Google 四处查看,不幸的是我没有任何具体的文章可供建议,但您肯定会找到一篇不错的文章),只需在构造函数中初始化您的字符串即可这样:

public ProjectData()
        {
            opcServerAddress = "Hello!";
        }

然后,由于绑定,文本框将具有您刚刚指定的默认值,并且每次修改它时,opcServerAddress 值都会根据文本框中的值进行更新。
这将特别允许您在 ProjectData 类(通常称为 ViewModel,如果您有时间,请查看 MVVM 模型)中使用此字符串:
需要良好的 WPF MVVM 教程

MVVM:从开始到结束的教程?
它非常有用,并且被认为是在 WPF 中工作的“正确”方式)

玩得开心! :)

You have to know that usually, if you want to implement a WPF application the "correct" way, your XAMLs will be bound to a ViewModel, keeping the properties.
I know it seems kinda heavy for the small amount of property you have to keep here, but believe me, it's awesome when you have bigger UIs.
You can also look around about Triggers which can help you validate something without adding a class (but would be VERY heavy if you have many fields to validate)
I'd advise you to check out this article which really helped me learn more about validation in WPF, if you haven't already read it:

http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

EDIT

For the default value:

Your Project data class has to implement the interface "INotifyPropertyChanged"
This allows to fire an event each time the text is changed, and therefore update the binding. Once you have done that (I'd encourage you to look around using Google, unfortunately I don't have any specific article to suggest, but you'll find a nice one for sure), just initialize your string in the constructor, something like that:

public ProjectData()
        {
            opcServerAddress = "Hello!";
        }

Then, thanks to the binding, the textbox will have the default value you just specified, and each time you modify it, opcServerAddress value will be updated following the value in the text box.
This will especially allow you to use this string in the ProjectData class (commonly called ViewModel, if you have time, check out the MVVM model:
Need good MVVM tutorial for WPF

MVVM: Tutorial from start to finish?
it is very useful, and it is considered to be the "proper" way to work in WPF)

Have fun! :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文