【发布时间】: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 中绑定到该属性。<Button Content="{Binding Content, RelativeSource={RelativeSource AncestorType=UserControl}}";在主窗口中,比如<local:MyButtonControl Content="Blah" /> -
@Ed 直到有另一个按钮...
-
@Clemens 在我看来,UserControl XAML 中只有一个按钮:“按钮”。
-
@Ed 当然,现在听起来是这样。仍然一般的方法是自定义属性。并且不要忘记您已经在其 XAML 中定义了 UserControl 的内容
标签: c# wpf user-controls