WPF:在样式资源中包含名称空间以访问转换器

时间:2015-10-31 12:17:17

标签: wpf namespaces

我很困惑为什么这不起作用,因为我看了很多例子,据我所知,我做的一切都是一样的!

下面我有一个单独的xaml文件,位于Project > Styles > Misc.xaml。我正在尝试引用命名空间,以便我可以在一个样式中使用此类中的类(Converter)。

P.S 我尝试添加程序集名称,这仍然不起作用,所有文件都在同一个程序集中。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:Test_Project.Styles"
                    xmlns:General="clr-namespace:Test_Project.Converters.General;assembly=Test_Project"
                    xmlns:CircularProgress="clr-namespace:Test_Project.Converters.CircleProgress">

    <FontFamily x:Key="FontAwesome">/Fonts/#FontAwesome</FontFamily>

    <!--<General:CheckBoxConverter x:Key="CheckBoxConverter" />-->
    <CircularProgress:StartPointConverter x:Key="StartPointConverter" />

xmlns:CircularProgress声明不会返回任何错误,但最后一行会返回以下错误:

  

名称“StartPointConverter”在命名空间“clr-namespace:Test_Project.Converters.CircleProgress”中不存在。

我试图引用的命名空间位于Project > Converters > CircleProgress.cs,下面是此命名空间的代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace Test_Project.Converters
{
    public class StartPointConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is double && ((double)value > 0.0))
            {
                return new Point((double)value / 2, 0);
            }

            return new Point();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }
}

有人可以向我解释我做错了什么!?谢谢。

修改 改变了

namespace Test_Project.Converters.CircleProgress

namespace Test_Project.Converters

并将xmlns声明更改为

xmlns:CircularProgress="clr-namespace:Test_Project.Converters"

对应,仍然得到相同的错误。

编辑2 更新了我上面的类代码,我有using System.Globalization;,我可能应该首先包括在内。

所以仍然得到错误,这是我的项目布局,我选择了上面提到的两个文件: enter image description here

2 个答案:

答案 0 :(得分:1)

您的namescpace与文件位置不对应。

namespace Test_Project.Converters.CircleProgress

应该是

namespace Test_Project.Converters

答案 1 :(得分:1)

在您添加了转换器的类文件中,您错过了:

using System.Globalization;

或者你需要(注意最后一个论点):

 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

哦顺便问一下,你有类似的帖子吗? https://stackoverflow.com/questions/33439436/wpf-referencing-namespace-not-working