我认为你的结论和推论并不完全正确。
第一件事在WPF 中,一切都源自DependencyObject。 FrameworkElement 类没有任何不同。如果您查看FrameworkElement 类的层次结构,如下所示:
DependencyObject --> Visual --> UIElement --> FrameworkElement
因此,如果您尝试在派生自上述任何类的类中创建 Dependency Property,它将正常工作(不包括直接绑定,但其他方式绑定工作(参见下面的示例))。您的CustomControl(不确定您使用的是CustomControl 还是UserControl)代码一定有问题。
但是从UIElement派生的类也可以有DependencyProperties,可以绑定到其他元素。
见UIElement类,它有很多DependencyProperties。
请分享您的控件代码,我们可以调查一下。
更新:
这是一个如何绑定DependecyObject's DependencyProperty 的示例:
DependencyObject 实施:
public class MyClass : DependencyObject
{
public MyClass()
{
this.Button = new Button();
Button.Width = 500;
Button.Height = 400;
Button.Content = "Bound to Window Height";
}
private Binding height;
public Binding Height
{
get { return height; }
set
{
height = value;
ApplyBinding();
}
}
public Button Button { get; set; }
private void ApplyBinding()
{
this.Button.SetBinding(Button.HeightProperty, this.Height);
}
}
使用我们的DependencyObject 实现的UserControl:
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public MyClass MyClass
{
get { return (MyClass)GetValue(MyClassProperty); }
set { SetValue(MyClassProperty, value); }
}
// Using a DependencyProperty as the backing store for MyClass. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyClassProperty =
DependencyProperty.Register("MyClass", typeof(MyClass), typeof(MyUserControl), new UIPropertyMetadata(new PropertyChangedCallback(MyClassPropertyChanged)));
private static void MyClassPropertyChanged(DependencyObject DO, DependencyPropertyChangedEventArgs e)
{
var MUC = DO as MyUserControl;
if (e.NewValue != null)
{
var myClass = e.NewValue as MyClass;
MUC.MyCanvas.Children.Add(myClass.Button);
}
}
}
最后绑定:
<Window x:Class="WpfStackOverflowTempProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"
xmlns:local="clr-namespace:WpfStackOverflowTempProject"
Height="{Binding ElementName=UIContent,Path=MyClass.HeightReplica,Mode=OneWayToSource}"
>
<local:MyUserControl x:Name="UIContent" >
<local:MyUserControl.MyClass>
<local:MyClass Height="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=ActualHeight,Mode=OneWay}" />
</local:MyUserControl.MyClass>
</local:MyUserControl>
所以当我们的Window 的Height 发生变化时,上述程序的输出,
它将反射回我们的MyClass 组件的按钮element
就像我们在 XAML 代码中绑定到 Button 本身一样。 所以
Myclass 是它的逻辑父控件和它的
用于指定公开属性/绑定的子元素
并定义它们对应于子元素的行为,
这实际上将在 UI 上可见,MyClass 仅适用
就像一个习惯用法的过滤器。