【问题标题】:Problem with static data binding in wpfwpf中的静态数据绑定问题
【发布时间】:2010-05-18 17:32:00
【问题描述】:

我对 wpf 比较陌生,我还不太了解绑定。

我想在我的应用程序中拥有多个包含相同项目的组合框。基本的解决方案是复制粘贴,但这不是一个好习惯。所以我想用我想要的内容放置一个静态资源并将所有组合框绑定到它。它编译并运行良好,但组合框为空。

代码如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<ItemsControl x:Key="Validations">
    <ItemsControl.Items>
        <ComboBoxItem>String</ComboBoxItem>
        <ComboBoxItem>Numeric</ComboBoxItem>
    </ItemsControl.Items>
</ItemsControl>

这是组合框:

<ComboBox ItemsSource="{Binding Source={StaticResource Validations}}"/>

我知道解决这个问题的方法可能很简单,但我还没有弄清楚。我会继续努力的;)

谢谢

【问题讨论】:

    标签: wpf data-binding combobox


    【解决方案1】:

    将资源设为字符串列表,而不是可视元素,然后使用 StaticResource 扩展名将其分配给 ItemsSource 属性,如下所示:

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:sys="clr-namespace:System;assembly=mscorlib"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <x:ArrayExtension x:Key="Data" Type="{x:Type sys:String}">
                <sys:String>String1</sys:String>
                <sys:String>String2</sys:String>
                <sys:String>String3</sys:String>
            </x:ArrayExtension>
        </Window.Resources>
        <Grid>
            <StackPanel>
                <ComboBox ItemsSource="{StaticResource Data}"/>
                <ComboBox ItemsSource="{StaticResource Data}"/>
                <ComboBox ItemsSource="{StaticResource Data}"/>
            </StackPanel>
        </Grid>
    </Window>
    

    注意xmlns:sys 命名空间的定义(映射到程序集mscorlib 中的命名空间System)以及使用x:ArrayExtension 元素在XAML 中声明一个简单数组。

    【讨论】:

    • 感谢您的帮助,但它没有用。它抛出异常:无法将属性“ItemsSource”中的值转换为“System.Collections.IEnumerable”类型的对象。 “System.Windows.Markup.ArrayExtension”不是属性“ItemsSource”的有效值。
    • 这已在 VS2010 上使用 .NET 4 进行了尝试和测试。-您使用的是相同的吗?
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多