带有嵌入式按钮的 Wpf 用户控件:更改按钮的内容

Wpf usercontrol with embedded button : change button's content

我有一个简单的用户控件,里面有一个我修改过的按钮。

当我将此用户控件添加到我的主窗口时,我只能访问该用户控件的属性。如何访问按钮内容?理想情况下,我想要一个自定义 属性 比方说 "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}"/>

绑定应如下所示:

<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 或类似的东西。