代码之家  ›  专栏  ›  技术社区  ›  Brownish Monster

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

  •  0
  • Brownish Monster  · 技术社区  · 11 年前

    问题

    我有一个 UserControl 其中包含 ToggleButton 和一个 ComboBox 。该控件将允许用户选择排序类型(通过 组合框 )和方向(通过 切换按钮 ). 我希望能够公开 组合框 以及更多,那么我如何绑定 组合框 Items 的属性 用户控制 ,我将自己实现,但也包括内置的 Content 财产——类似于 组合框 两者都可以。

    用户控制

    我有一个用户控件,其设置与下面的代码类似,或者 look here .

    <UserControl x:Class="Example.DirComboBox">
        <Grid>
            <ComboBox x:Name="cbItems" />
            <ToggleButton x:Name="tbSortDir"/>
        </Grid>
    </UserControl>
    

    控件使用

    我希望能够以两种方式使用它:

    1:

    添加子元素。

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

    2:

    结合 项目 所有物

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

    选择

    我愿意使用替代方案,例如将根设置为 组合框 而不是 用户控制 但我需要暴露以下内容(但不确定如何暴露):

    1. 有一个 切换按钮 另外
    2. SortDirection 属性为布尔
    3. RoutedEvent 对于 Ascending Descending
    2 回复  |  直到 11 年前
        1
  •  0
  •   Nitin Purohit    11 年前

    定义的依赖性财产 SortDirection , Items 在您的 usercontrol 。在控件中包含这些财产后,可以从外部直接设置它们,如:

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

    然后在控件内将这些财产绑定到相应的控件,如:

    <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>
    

    保持双向绑定模式。

        2
  •  0
  •   Brownish Monster    11 年前

    而不是基于我的控制 UserControl 我根据更改为使用CustomControl the Tutorial on MSDN .