【问题标题】:How to parse an XML attribute for a WPF binding如何解析 WPF 绑定的 XML 属性
【发布时间】:2015-02-19 23:57:34
【问题描述】:

首先,了解我正在处理在运行时从 XML 生成的动态接口。我编写了 XAML,它打开各种元素和属性以创建适当的控件和标签,以便显示增强的 XML 文件中包含的数据。

示例 XML 片段:

   <floop Format="combo" Choices="apple;banana;cherry" Value="cherry"/>

格式和值已经有效。我正在寻找一种使选择起作用的方法。 (是的,这对于 XML 来说是非常规的,但它现在可以达到目的。)

这是一个提议的 XAML 片段:

 <ComboBox Style="{StaticResource ComboButtonStyle}"  
         Width="200"
         ItemsSource="{Binding XPath=@Choices}" IsEditable="True"
         />

问题是,@Choices 是单个字符串,所以我建议解析字符串以生成 ItemsSource 所需的数据类型。

从这里到那里怎么走?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您想在 Binding 上使用转换器将其从字符串转换为列表。 This answer 则相反。

    我还没有测试过这段代码,但它应该能让你到达你想去的地方。

    &lt;ComboBox Style="{StaticResource ComboButtonStyle}" Width="200" ItemsSource="{Binding XPath=@Choices, Converter={StaticResource StringToListConverter}}" IsEditable="True" /&gt;

    [ValueConversion(typeof(string), typeof(List<string>))]
    public class StringToListConverter : IValueConverter
    {
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(List<string>))
                throw new InvalidOperationException("The target must be a List<string>");
    
            return new List<string>(((string)value).Split(';'));
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    【讨论】:

    • 为了修复,我将 添加到 Resounces,并将 Converter 引用更改为 Converter={StaticResource stringToListConverter}
    • 好的,下一个问题:Convert 正在接收 XmlDataCollection 和 System.Collections.IEnumerable,而不是字符串和 List。我可以切换后者的类型,但是这个 XmlDataCollection 是怎么回事?
    • @AlanBaljeu 看起来它会使用它而不仅仅是一个字符串。我不会担心的。尝试将string 更改为XmlDataCollection,看看你是否可以让它工作。您将不得不稍微调整代码。至于转换器,我知道您必须进行额外的更改,但您的做法是合适的。
    • 我最终做了什么以供将来参考:删除 XPath=@choices,然后在转换器中接收一个 XML 元素。从那里我可以编写 C# 来访问 XmlElement 中的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多