【问题标题】:Windows 8 ListBox DatabindingWindows 8 列表框数据绑定
【发布时间】:2012-11-15 21:17:14
【问题描述】:

我有一个列表框,我正在尝试使用“metro”应用程序进行数据绑定。这是我的 xaml:

    <ListBox x:Name="ImagesList" Margin="40" Grid.Row="1">
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Key}" />
            </StackPanel>
        </DataTemplate>
    </ListBox>

我已经创建了一个来源:

        List<KeyValuePair<string, string>> items = 
            new List<KeyValuePair<string, string>>();

        items.Add(new KeyValuePair<string, string>("a", "a"));
        items.Add(new KeyValuePair<string, string>("b", "b"));
        items.Add(new KeyValuePair<string, string>("c", "c"));
        this.ImagesList.ItemsSource = items;

我希望这会在我的应用程序 a、b 和 c 中创建一个文本列表

但是,我为我绑定的每个元素获取了以下文本:

System.Runtime.InteropServices.CLRKeyBaluePairOmpl'2[System.String, System.String]

看起来它正在显示我正在绑定的类型的全名......我做错了什么?

【问题讨论】:

    标签: data-binding windows-8 listbox


    【解决方案1】:

    您需要将Converter 分配给Binding

    将转换器转换为 XAML 资源

    <src:KeyValueConverter:Key="KeyConverter"/>
    

    将绑定转换器添加到文本源

    Text="{Binding Path=ItemsList, Converter={StaticResource KeyConverter}}"
    

    示例转换器代码

    public class KeyValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var kvp = (KeyValuePair)value;
            return kvp.Key;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    【讨论】:

    • 我将把它标记为答案,因为我相信它适用于我的 KVP 示例。
    【解决方案2】:

    我的 Xaml 也应该是错误的:

     <ListBox x:Name="ImagesList" Margin="40" Grid.Row="1">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Value}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-30
      • 2012-05-30
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2014-04-17
      相关资源
      最近更新 更多