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()
{
}
}