如何在 WPF XAML 中声明命名空间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2088754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:25:34  来源:igfitidea点击:

How to declare a namespace in WPF XAML?

wpfvalidationxamlnamespaces

提问by rem

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:

我试图在 WPF 中使用带有验证规则的数据绑定控件的验证输入。在 wpf 窗口的代码隐藏文件中,我有一个类:

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.

在 XAML 中还有一个样式错误模板。

When I put a textbox with validation in XAML:

当我在 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.

我收到一个编译时错误: “local”是一个未声明的命名空间。XML 无效。

How I should declare local:posintValidationRulein my XAML?

我应该如何local:posintValidationRule在 XAML 中声明?

回答by StrayPointer

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:

在 XAML 文件的顶部,您需要声明“本地”命名空间是什么;与默认的 Microsoft XAML 内容一起使用。像这样的东西:

xmlns:local="clr-namespace:YourApplication"

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

请注意,这假设在“YourApplication”的根命名空间中定义了“posintValidationRule”。