Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a namespace in WPF XAML?

I am trying to use in WPF a validating input of databound controls with validation rules. In the code behind file of a wpf window I have a class:

public class posintValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        string _strInt = value.ToString();
        int _int = -1;
        if (!Int32.TryParse(_strInt, out _int))
            return new ValidationResult(false, "Value must be an integer");
        if (_int < 0)
            return new ValidationResult(false, "Value must be positive");
        return new ValidationResult(true, null);
    }
}

In XAML there is also a style error template.

When I put a textbox with validation in XAML:

<TextBox.Text>
    <Binding Path="seconds" UpdateSourceTrigger="PropertyChanged">
        <Binding.ValidationRules>
           <local:posintValidationRule/> 
        </Binding.ValidationRules>
    </Binding>
</TextBox.Text>

I get a compile time error: ''local' is an undeclared namespace.' XML is not valid.

How I should declare local:posintValidationRule in my XAML?

like image 640
rem Avatar asked Jan 18 '10 19:01

rem


People also ask

How do I add a namespace in XAML?

The techniques of specifying a XAML namespace rely on the XML namespace syntax, the convention of using URIs as namespace identifiers, using prefixes to provide a means to reference multiple namespaces from the same markup source, and so on.

What is XAML namespace declaration?

A XAML namespace is a specialized XML namespace, just as XAML is a specialized form of XML and uses the basic XML form for its markup. In markup, you declare a XAML namespace and its mapping through an xmlns attribute applied to an element.

What is the namespace that is used for WPF?

WPF uses XML Namespaces, as defined by the W3C. Namespaces are used to prevent conflicts from occurring, to distinguish code from developers. To solve problems where two developers may use the same elements in their code, namespaces and prefixes are used.

Which of the following attributes in WPF can reference the XAML namespace?

The xmlns attribute specifically indicates the default XAML namespace. Within the default XAML namespace, object elements in the markup can be specified without a prefix.


1 Answers

At the top of your XAML file, you need to declare what your "local" namespace is; alongside the default Microsoft XAML stuff. Something like this:

xmlns:local="clr-namespace:YourApplication"

Note this assumes that "posintValidationRule" is defined at the root namespace in "YourApplication".

like image 72
StrayPointer Avatar answered Oct 07 '22 12:10

StrayPointer