开发者

C# WPF Bindings, ValidationRule and default value

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 RelativeSour开发者_运维问答ce.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()
        {
        }
    }


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! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜