将 ComboBoxItem 添加到用户控件内的组合框 (XAML/WPF) [英] Adding ComboBoxItem to a combobox inside a user control (XAML/WPF)

查看:27
本文介绍了将 ComboBoxItem 添加到用户控件内的组合框 (XAML/WPF)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习在 WPF 中创建自定义控件.我使用标签和文本框成功创建了一个简单的自定义控件.我能够允许通过 DependencyProperty 设置标签文本.

I am currently learning to create custom controls in WPF. I successfully created a simple custom control using a Label and a Text Box. I was able to allow setting the Label text by DependencyProperty.

现在我正在创建一个具有 ComboBox 的用户控件.我需要允许从控件外部向此 ComboBox 添加项目.

Now I am creating a user control that has a ComboBox. I need to allow adding items to this ComboBox from outside the control.

为了实现这一点,我尝试公开 ItemsCollection 类型的 DependencyProperty,它将允许访问 ComboBox 的 Items 属性(我的控件示例中的 DP 名为CbItems").但是我收到错误,因为 Combobox 的 Items 属性是只读的.

To achieve this, I tried exposing a DependencyProperty of type ItemsCollection and it will allows access to the ComboBox's Items property (the DP in my control sample is named 'CbItems'). But I get errors because Items property of Combobox is ReadOnly.

控制 XAML

<UserControl x:Class="MyWpfApp.Controls.MyControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="Auto" Width="Auto">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions> 
        <Label Grid.Column="0" Content="{Binding FieldLabel}"></Label>       
        <ComboBox Name="cmb"  Grid.Column="1" Width="150"></ComboBox>
    </Grid>
</UserControl>

主窗口 XAML

<Window x:Class="MyWpfApp.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ctl="clr-namespace:MyWpfApp.Controls"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <ctl:MyControl>
            <ctl:MyControl.CbItems>
                <ComboBoxItem>Hello</ComboBoxItem>
                <ComboBoxItem>World</ComboBoxItem>
                <ComboBoxItem>Hi</ComboBoxItem>
            </ctl:LobCombox.CbItems>
        </ctl:LobCombox>
    </Grid>
</Window>

我想知道实现此功能的正确方法是什么.我相信这个答案也可能对 GridView 等其他控件有所帮助

I would like to know what the correct way is to achieve this functionality. I believe the answer to this might also help with other controls like GridView etc

非常感谢

推荐答案

这篇很棒的文章来自Dr.WPF 包含您需要的所有信息,以及您可以使用的所有选项的详细说明.

This great article from Dr. WPF contains all the information you will need, and a thorough explanation of all the options you can utilize.

这篇关于将 ComboBoxItem 添加到用户控件内的组合框 (XAML/WPF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆