简体   繁体   English

如何公开用户控件内部的控件的属性?

[英]How to Expose Properties of a Control that is Inside a User Control?

For example, I have a button that is inside a User Control, and I would like to expose its own properties, so whenever somebody is using the User Control could easily change its button's properties values. 例如,我有一个位于用户控件内的按钮,并且我想公开其自己的属性,因此无论何时有人使用用户控件,都可以轻松地更改其按钮的属性值。 I was actually able to accomplish this in two ways: 实际上,我可以通过两种方式完成此任务:

First, Bind the Button's property such as, FontSize to its equivalent in the UserControl: 首先,将Button的属性(例如FontSize)绑定到UserControl中的等效属性:

<Button FontSize="{Binding Path=FontSize, ElementName=UserControl}" />

Second, Bind the Button's property to a new Dependency Property that is added to the User Control. 其次,将Button的属性绑定到添加到用户控件的新的Dependency属性。

<Button Content="{Binding Path=DependencyProperty, ElementName=UserControl}"

The question now, is there any way to access the Button's properties directly in XAML without doing any bindings to the User Control? 现在的问题是,有什么方法可以直接在XAML中访问Button的属性,而无需对用户控件进行任何绑定?

It's not really desired to name Controls in WPF. 在WPF中实际上并不需要命名Controls What you can do is use binding on the Parent using it's type rather than naming it. 您可以做的是使用Parent类型的绑定而不是命名它的类型。

<Button FontSize="{Binding FontSize, RelativeSource={RelativeSource Mode=FindAncestor, 
                   AncestorType={x:Type UserControl}}}" />

It's the easiest way. 这是最简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM