【问题标题】:WPF ListBox Binding ItemsSourceWPF ListBox 绑定 ItemsSource
【发布时间】:2010-11-05 14:59:07
【问题描述】:

related question 中,我询问了如何绑定到由另一个属性索引的数组的特定元素。提供的答案对于提供的示例代码示例非常有效。

我遇到麻烦的地方是我为 ListBox 指定了一个 ItemSource,当我单步执行它时,我在转换器中得到了一个 DependencyProperty.UnsetValue。毫无疑问,这是我对Binding的理解的问题。

我的列表框是这样的:

<ListBox ItemsSource="{Binding Path=MyList}">
    <ListBox.Resources>
        <local:FoodIndexConverter x:Key="indexConverter" />
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock>
                <TextBlock.Text>
                    <MultiBinding Converter="{StaticResource indexConverter}">
                        <Binding Path="MyIndex" />
                        <Binding Path="Fields" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

后面的代码如下:

public MainWindow()
{
    InitializeComponent();
    MyList.Add(new SomeData() { Fields = new object[] {"liver", "onions", "cake" } } );
    MyList.Add(new SomeData() { Fields = new object[] {"liver", "onions", "candy" } } );
    MyList.Add(new SomeData() { Fields = new object[] {"liver", "onions", "pie" } } );

    DataContext = this;
}

MyList 是一个列表。

MyIndex 是一个整数。

转换器代码是

    public class FoodIndexConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values == null || values.Length != 2)
                return null;

            int? idx = values[0] as int?;
            object[] food = values[1] as object[];

            if (!idx.HasValue || food == null)
                return null;

            return food[idx.Value];
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

当我在转换器代码中单步调试调试器时,MyIndex (value[0]) 为 DependencyProperty.UnsetValue - 对象数组与我预期的一样。

我假设这是一个绑定问题: 因为它不知道 MyIndex 是什么。

如果 MyIndex 是 SomeData 类的属性,它会按我的预期工作,但它不是,它是 MainWindow 类的属性,就像 MyList 一样。

如何指定我对属于我的 DataContext 而不是 MyData 列表的 MyIndex 属性感兴趣?

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

    它正在查找 ListBoxItem 上的 MyIndex 属性(在本例中为 SomeData 类),但该属性不存在。

    将绑定中的 ElementName 设置为窗口名称,使其在别处查找属性。

    <Binding ElementName=RootWindow, Path=DataContext.MyIndex />
    

    【讨论】:

    • 是的 - 很棒。像冠军一样工作。这是美好的一天——我学到了一些东西。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2011-07-13
    • 2015-04-07
    • 2012-02-18
    • 2011-12-17
    • 2011-10-26
    • 2011-01-14
    相关资源
    最近更新 更多