【发布时间】: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