2016-04-28 164 views
0

我有如下定义自定义属性自己的自定义控制:C#WPF引用自定义控制XAML中自定义属性值

public partial class MyControl : UserControl 
{ 
    public CustomProperty X 
    { 
     get { return (CustomProperty) GetValue(XProperty); } 
     set { SetValue(XProperty, value); } 
    } 

    public static readonly DependencyProperty XProperty = DependencyProperty.Register(
     "X", typeof (CustomProperty), typeof (MyControl), null); 

    public MyControl() 
    { 
     InitializeComponent(); 
    } 
} 

假设我在XAML中设置X值是这样的:

<controls:MyControl X="{Binding CustomPropertyValue}" /> 

我怎样才能在MyControl XAML代码访问,如果它是这样定义的X的值:

<UserControl> 
    <Button Content="<!--What to put here to access X?-->" /> 
</UserControl> 
+0

试试这个''。 – XAMlMAX

回答

1

你想从它内部绑定到UserControl的属性。这样做的最简单方法是使用“的ElementName”结合的方法(通常Visual Studio的名称,这些“用户控件”),所以你会拥有:

<Button Content="{Binding MyProperty, ElementName=userControl}"/> 

我永远记得这个时候,我开始的,但如果你点击在设计师的小框,然后选择“创建数据绑定”你可以通过一个很好的向导结合:

enter image description here

让你可以买性关中控制所有元素。下面是一个例子结合使用的ElementName被称为“说明”的属性:

enter image description here

值得注意的是,我发现这个经常需要构建之前列表中包含新的自定义依赖属性。

这是一个很好的界面,用于探索如何以各种方式创建绑定。你很可能也与“FindAncestor”而不是“的ElementName”做到这一点,沿东西线结束:

<Button Content="{Binding Description, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyCustomControlType}}}"/> 

但命名可能是更加容易和高效。