简体   繁体   English

我应该如何将组合框的ItemsSource绑定到Content和Items

[英]How should I bind a Combobox's ItemsSource to Content and Items

Problem 问题

I have a UserControl which contains a ToggleButton and a ComboBox . 我有一个包含一个ToggleButton和一个ComboBoxUserControl 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绑定到UserControlItems属性,我将自己实现它,以及内置的Content属性-类似于ComboBox可以同时完成这两项操作。

UserControl 用户控件

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>

Control Usage 控制用法

I would like to be able to use it in two ways: 我希望能够以两种方式使用它:

1: 1:

Adding Child Elements. 添加子元素。

<local:DirComboBox>
    <ComboboxItem Content="Item 1"/>
</local:DirComboBox>

2: 2:

Binding Items Property. 绑定Items属性。

<local:DirComboBox Items="{Binding SortList}"/>

Alternatives 备择方案

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但我需要公开以下内容(但不确定如何做):

  1. Have a ToggleButton on the side, 侧面有一个ToggleButton
  2. SortDirection property as a bool SortDirection属性为布尔值
  3. RoutedEvent for Ascending and Descending RoutedEvent AscendingDescending

Define Dependancy Properties for SortDirection , Items in your usercontrol . usercontrolSortDirection 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.

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