在 WPF 中,通过 ControlTemplate 定义的自定义 ComboBox,可以使用'ItemsControl.Items' 属性来获取 ComboBox 中的项。以下是一个示例:

<ControlTemplate TargetType="ComboBox" x:Key="CustomComboBoxTemplate">
    <Grid>
        <ToggleButton x:Name="PART_ToggleButton" Content="Toggle" />
        <Popup x:Name="PART_Popup" IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom">
            <Grid>
                <Border Background="White" BorderBrush="Black" BorderThickness="1">
                    <ItemsPresenter />
                </Border>
            </Grid>
        </Popup>
    </Grid>
</ControlTemplate>

在代码中,可以使用'GetTemplateChild' 方法来获取 ComboBox 中的元素,并通过强制类型转换为 ComboBox 类型,然后使用'Items' 属性来获取项。以下是一个示例:

ComboBox comboBox = (ComboBox)customComboBox.Template.FindName("PART_ComboBox", customComboBox);
if (comboBox != null)
{
    foreach (var item in comboBox.Items)
    {
        // 处理每个项
    }
}

请确保在使用'GetTemplateChild' 方法之前,已经应用了 ControlTemplate,并且在找到 ComboBox 元素之后进行了 null 检查。

WPF ControlTemplate ComboBox 获取 item 内容

原文地址: https://www.cveoy.top/t/topic/bHeG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录