简体   繁体   English

C#WPF绑定,ValidationRule和默认值

[英]C# WPF Bindings, ValidationRule and default value

I new to WPF and C# and I have a problem with my application. 我是WPF和C#的新手,我的应用程序有问题。 I have a TextBox which I want to have a ValidationRule on to validate the text. 我有一个TextBox,想要在其中启用ValidationRule来验证文本。 Now I want to have a default value in the TextBox but i can't figure out how to do it. 现在我想在TextBox中有一个默认值,但是我不知道该怎么做。 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? 还有没有使用ProjectData类文件的方法吗? 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: 我的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);
        }
    }

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: 我的ProjectData文件如下所示:

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

        public ProjectData()
        {
        }
    }

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. 您必须知道,通常,如果您想以“正确”的方式实现WPF应用程序,则XAML将绑定到ViewModel,并保留属性。 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. 我知道这对于您必须保留在此处的少量属性似乎有点沉重,但是请相信我,当您拥有较大的UI时,这真棒。 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: 您还可以查看有关触发器的信息,该触发器可以帮助您无需添加类就可以验证某些内容(但是如果您有很多要验证的字段,那将非常繁琐)。我建议您阅读这篇文章,它确实帮助我在WPF,如果您尚未阅读它:

http://www.codeproject.com/KB/WPF/wpfvalidation.aspx 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. 您的Project数据类必须实现“ INotifyPropertyChanged”接口,该接口允许每次更改文本时触发一个事件,从而更新绑定。 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: 完成此操作后(建议您使用Google环顾四周,不幸的是,我没有任何具体的文章可以建议,但您肯定会找到不错的文章),只需在构造函数中初始化字符串即可像那样:

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. 然后,由于有了绑定,文本框将具有您刚指定的默认值,并且每次对其进行修改时,opcServerAddress值将在文本框中的值之后进行更新。 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 这将特别允许您在ProjectData类中使用此字符串(通常称为ViewModel,如果您有时间,请查看MVVM模型: WPF需要良好的MVVM教程

MVVM: Tutorial from start to finish? MVVM:教程从头到尾? it is very useful, and it is considered to be the "proper" way to work in WPF) 这非常有用,并且被认为是在WPF中“正确”的工作方式)

Have fun! 玩得开心! :) :)

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

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