说我有一个自定义的数据类型,看起来像这样:
- public class MyDataType
- {
- public string SimpleProp1;
- public string SimpleProp2;
- public List<SomeType> ComplexProp;
- }
现在我制作了动态创建的数据绑定控件(即ItemsControl或DataGrid).
xaml代码中定义的绑定如何处理复杂属性的子属性?我以为应该看起来像这样:
- <TextBox Text="{Binding simpleSubProp,path=ComplexProp[0]}" />
要么
- <TextBox Text="{Binding path=ComplexProp[0].simpleSubProp}" />
但是这两个都给我xml解析错误.它应该如何正确看?甚至可以以一种方式引用一个收集属性的特定项目?如果不是,还有什么其他选择?
编辑,情景似乎不够清楚:
我有一个
- IEnumberable<MyDataType>
这绑定到一个ItemsControl,在DataTemplate内部,我有多个TextBoxes需要引用复杂属性列表中的一个对象的子属性.
解决方法
看起来像Silverlight
Indexers in property paths are broken中的恶意路径索引器是破碎的.绕过它的方式是在帖子中建议的,并使用IValueConverter.
XAML
- <UserControl x:Class="Silverlight.Mine.Page"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:sys="System"
- xmlns:sm="clr-namespace:Silverlight.Mine;assembly=Silverlight.Mine"
- Width="400" Height="300">
- <UserControl.Resources>
- <sm:SomeTypeConverter x:Key="MySomeTypeConverter" />
- </UserControl.Resources>
- <Grid x:Name="LayoutRoot" Background="White">
- <TextBlock x:Name="myTextBlock" Text="{Binding Path=SomeDates,Converter={StaticResource MySomeTypeConverter}}" />
- </Grid>
- </UserControl>
C#Page.xaml.cs
- namespace Silverlight.Mine
- {
- public partial class Page : UserControl
- {
- private SomeType m_mySomeType = new SomeType();
- public Page()
- {
- InitializeComponent();
- myTextBlock.DataContext = m_mySomeType;
- }
- }
- }
C#SomeType.cs
- namespace Silverlight.Mine
- {
- public class SomeType
- {
- public List<DateTime> SomeDates { get; set; }
- public SomeType()
- {
- SomeDates = new List<DateTime>();
- SomeDates.Add(DateTime.Now.AddDays(-1));
- SomeDates.Add(DateTime.Now);
- SomeDates.Add(DateTime.Now.AddDays(1));
- }
- }
- public class SomeTypeConverter : IValueConverter
- {
- public object Convert(object value,Type targetType,object parameter,CultureInfo culture)
- {
- if (value != null)
- {
- List<DateTime> myList = (List<DateTime>)value;
- return myList[0].ToString("dd MMM yyyy");
- }
- else
- {
- return String.Empty;
- }
- }
- public object ConvertBack(object value,CultureInfo culture)
- {
- if (value != null)
- {
- return (List<DateTime>)value;
- }
- return null;
- }
- }
- }