【问题标题】:How to store and retrieve attributes of ComboBoxItem in xaml file?如何在 xaml 文件中存储和检索 ComboBoxItem 的属性?
【发布时间】:2012-01-12 00:21:44
【问题描述】:

我有一个包含大约 20 个项目的组合框。我想为每个 ComboBoxItem 关联最多 5 个属性,例如颜色、价格、运输重量等。

我想将所有这些属性存储在 xaml 文件中,并在 C# 代码中选择项目时检索它们。

如何才能最好地做到这一点?将所有内容存储在 Tag 中并解析 Tag 字符串是最好的方法吗?谢谢。

 <ComboBoxItem Content="Shirt" Tag="Red;14;2"></ComboBoxItem>

【问题讨论】:

    标签: c# wpf xaml combobox tags


    【解决方案1】:

    您可以在标签中存储任何内容,如果您想要更多类型安全,请创建一个对象:

    <ComboBoxItem>
        <ComboBoxItem.Tag>
            <local:Attributes Color="Red" Min="2" Max="14"/>
        <ComboBoxItem.Tag>
    <ComboBoxItem>
    

    但更好的是,您不应该自己创建项目,而只需使用 ComboBox.ItemsSourceItemTemplate 拥有一个项目集合和 bind/data template,然后您可以将其与项目一起存储。

    ComboBox.SelectedItem 将直接成为具有您需要的所有属性的此类项目。

    【讨论】:

    • 您能告诉我如何使用您的示例检索 Color 属性吗?现在我正在使用 ...(comboBox1.SelectedItem).Tag.ToString() 来检索标签的值。谢谢。
    • @user763554:如果标签是如上所示的对象,您只需将其转换,例如var atts = ((Attributes)((ComboBoxItem)comboBox1.SelectedItem).Tag; 那么你可以用atts.Color 做一些事情。 (如果您是 XAML 新手,您可能也对 that overview 感兴趣)
    猜你喜欢
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 2013-06-10
    • 1970-01-01
    • 2020-06-09
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多