2017-06-20 72 views
0

我有一个简单的用户控件,它包含一个我修改过的按钮。带有嵌入式按钮的Wpf用户控件:更改按钮的内容

当我将此用户控件添加到我的主窗口时,我只能访问usercontrol的属性。我如何访问按钮内容?理想情况下,我想有一个自定义属性让我们说“TheText”,我改成了这样

<local:MyButtonControl TheText="My text here will be the button content"> 

这是我在用户控件“MyButtonControl”

public object TheText 
     { 
      get => (object)GetValue(_text); 
      set => SetValue(_text, value); 
     } 
     public static readonly DependencyProperty _text = 
      DependencyProperty.Register("Text", typeof(object), typeof(MyButton), new UIPropertyMetadata(null)); 

但我是什么应该把绑定?无法弄清楚。这是关注的按钮。

<Button x:Name="button" Content="{Binding ??? }" Style="{StaticResource RoundedButton}"/> 
+0

“理想情况下,我想拥有一个自定义属性”。做到这一点。在UserControl中声明一个名为TheText的依赖属性,并将Button的内容绑定到该属性。有关示例,请参见[这里](https://stackoverflow.com/a/44649504/1136211)。 – Clemens

+0

您不需要新的依赖属性,只需使用USerControl的现有'Content'属性并将其绑定到UserControl XAML中的属性即可。 '

+0

@Ed直到有另一个Button ... – Clemens

回答

1

的结合应该是这样的:

<Button Content="{Binding Text, 
    RelativeSource={RelativeSource AncestorType=UserControl}}" .../> 

注意正确的依赖项属性声明必须使用同名字的依赖项属性和CLR包装。还有一个约定将标识符字段命名为<PropertyName>Property

public object Text 
{ 
    get => (object)GetValue(TextProperty); 
    set => SetValue(TextProperty, value); 
} 

public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register("Text", typeof(object), typeof(MyButton)); 

你当然应该也使用string作为一个类型被称为Text财产。或者你致电ButtonContent或类似的东西。

+0

@EdPlunkett太晚了,不过谢谢! ;) – user3673720