[英]How should I bind a Combobox's ItemsSource to Content and Items
I have a UserControl
which contains a ToggleButton
and a ComboBox
. 我有一个包含一个
ToggleButton
和一个ComboBox
的UserControl
。 The control will allow the user to choose a sort type (via ComboBox
) and a Direction (via ToggleButton
). 该控件将允许用户选择排序类型(通过
ComboBox
)和方向(通过ToggleButton
)。 I want to be able to expose some properties of the ComboBox
and more, so how do I bind the ItemsSource of the ComboBox
to an Items
Property of the UserControl
, which I will implement myself, but also the built-in Content
property---similar to how a ComboBox
can do both. 我希望能够公开
ComboBox
某些属性以及更多属性,所以如何将ComboBox
的ItemsSource绑定到UserControl
的Items
属性,我将自己实现它,以及内置的Content
属性-类似于ComboBox
可以同时完成这两项操作。
I have a user control which set-up is similar as the below code, or look here . 我有一个用户控件,其设置类似于以下代码,或在此处查看 。
<UserControl x:Class="Example.DirComboBox">
<Grid>
<ComboBox x:Name="cbItems" />
<ToggleButton x:Name="tbSortDir"/>
</Grid>
</UserControl>
I would like to be able to use it in two ways: 我希望能够以两种方式使用它:
Adding Child Elements. 添加子元素。
<local:DirComboBox>
<ComboboxItem Content="Item 1"/>
</local:DirComboBox>
Binding Items
Property. 绑定
Items
属性。
<local:DirComboBox Items="{Binding SortList}"/>
I would be willing to use alternatives, such as setting the root as ComboBox
instead of UserControl
but I need to expose the follow (but not sure how): 我愿意使用替代方法,例如将根目录设置为
ComboBox
而不是UserControl
但我需要公开以下内容(但不确定如何做):
ToggleButton
on the side, ToggleButton
, SortDirection
property as a bool SortDirection
属性为布尔值 RoutedEvent
for Ascending
and Descending
RoutedEvent
Ascending
和Descending
Define Dependancy Properties for SortDirection
, Items
in your usercontrol
. 在
usercontrol
为SortDirection
Items
定义依赖项属性。 Once you have these properties in your control you can directly set them from outside like: 在控件中拥有这些属性后,您可以直接从外部进行设置,例如:
<local:DirComboBox Items="{Binding SortList}" SortDirection="{Binding Sort}"/>
then inside your control bind these properties to respective controls like: 然后在控件内部将这些属性绑定到各个控件,例如:
<UserControl x:Class="Example.DirComboBox">
<Grid>
<ComboBox x:Name="cbItems" ItemsSource="{Binding Items, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}"}/>
<ToggleButton x:Name="tbSortDir" IsPressed="{Binding SortDirection, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}"/>
</Grid>
</UserControl>
keep the binding mode as twoway. 保持绑定模式为双向。
不再将控件置于UserControl
上,而是根据MSDN上的教程改为使用CustomControl。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.