C# 通过XAML在属性中添加类的实例

C# 通过XAML在属性中添加类的实例,c#,wpf,xaml,C#,Wpf,Xaml,我有一个自定义类(按钮扩展类),其中我有一个Control类型的自定义属性。 我需要此属性来访问另一个控件并执行某些操作 财产声明如下: private Control mainTab = null; public Control MainTab { get { return mainTab; } set { mainTab = value; } } 但在XAML中,当我使用: // "mainTab" is the x:Name of another control in this wind

我有一个自定义类(按钮扩展类),其中我有一个Control类型的自定义属性。 我需要此属性来访问另一个控件并执行某些操作

财产声明如下:

private Control mainTab = null;
public Control MainTab { get { return mainTab; } set { mainTab = value; } }
但在XAML中,当我使用:

// "mainTab" is the x:Name of another control in this window
<CustomClass MainTab="mainTab" ....></CustomClass>
/“mainTab”是此窗口中另一个控件的x:名称

我得到“Memeber MainTab无法识别或无法访问”。为什么?

在xaml中包含自定义类的名称空间,然后可以使用自定义类

    <Window x:Class="WpfApplication2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WpfApplication2"
            Title="MainWindow" Height="350" Width="525">
 <Canvas>
        <local:CustomClass MainTab=""/>

    </Canvas>

通过设置绑定的
ElementName
属性,使用到命名元素的绑定:

<local:CustomClass MainTab="{Binding ElementName=mainTab}" ... />

尝试将MainTab设置为依赖属性,并将控件(使用elementname)绑定到它。在XAML中只能访问依赖项属性。@核心一:不,这不是真的。但是它们不会更新,除非它是
dependencProperty
,或者该类实现了
INotifyPropertyChanged
@Core-One。很可能在XAML中设置非依赖性属性。但是,他们不能成为绑定的目标。谢谢。这正是我想要的。
<local:CustomClass MainTab="{Binding ElementName=mainTab}" ... />
public static readonly DependencyProperty MainTabProperty =
    DependencyProperty.Register(
        "MainTab", typeof(Control), typeof(CustomClass));

public Control MainTab
{
    get { return (Control)GetValue(MainTabProperty); }
    set { SetValue(MainTabProperty, value); }
}