【问题标题】:Wpf usercontrol with embedded button : change button's content带有嵌入式按钮的 Wpf 用户控件:更改按钮的内容
【发布时间】:2017-06-20 17:24:55
【问题描述】:

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

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

【问题讨论】:

  • “理想情况下,我想拥有一个自定义属性”。做到这一点。在 UserControl 中声明一个名为 TheText 的依赖属性,并将 Button 的 Content 绑定到该属性。有关示例,请参见 here
  • 您不需要新的依赖属性,只需使用 USerControl 的现有 Content 属性并在您的 UserControl XAML 中绑定到该属性。 &lt;Button Content="{Binding Content, RelativeSource={RelativeSource AncestorType=UserControl}}";在主窗口中,比如&lt;local:MyButtonControl Content="Blah" /&gt;
  • @Ed 直到有另一个按钮...
  • @Clemens 在我看来,UserControl XAML 中只有一个按钮:“按钮”。
  • @Ed 当然,现在听起来是这样。仍然一般的方法是自定义属性。并且不要忘记您已经在其 XAML 中定义了 UserControl 的内容

标签: c# wpf user-controls


【解决方案1】:

绑定应该是这样的:

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

请注意,正确的依赖属性声明必须对依赖属性和 CLR 包装器使用相同的名称。还有一个约定,将标识符字段命名为&lt;PropertyName&gt;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 或类似的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-29
    • 2011-08-20
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多