如何在wpf资源中创建对公共类的引用?

时间:2017-01-26 08:14:38

标签: c# wpf xaml

在这个最微不足道的例子中,我无法弄清楚我做错了什么。如何在项目的本地命名空间中创建引用公共类的资源?

在MainWindow.xaml:

<Window x:Class="Foo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Foo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <local:Bar x:Key="MyBar" /><!-- problem here -->
        </Grid.Resources>

    </Grid>
</Window>

在MainWindow.xaml.cs中:

namespace Foo
{
    public class Bar
    {

    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

当我这样做时,我收到错误The name "Bar" does not exist in the namespace "clr-namespace:Foo".

这个问题几乎与this related question相同,但我的课程已经公开。

2 个答案:

答案 0 :(得分:0)

只需构建项目,它应该工作,这是正确的。

答案 1 :(得分:-1)

尝试从UserControl继承您的类

public class Bar : UserControl
{

}

https://msdn.microsoft.com/en-us/library/ms753379.aspx