【发布时间】:2015-07-07 07:36:07
【问题描述】:
我想使用DataTemplate 将Dictionary<DateTime, MyClass> 绑定为StackPanel 的ItemSource。它适用于Collection<DateTime>,但似乎无法掌握字典的语法。
如果我只绑定DateTime 类型的字典键,则下面的 xaml 文件有效。但我也想访问价值。值是 MaClass 类型,我还需要将各种成员(FromDate、ToDate)放入网格中。提前谢谢你们!
.xaml 文件
<DataTemplate x:Key="Mytemplate" DataType="x:Type local:MyClass">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding Key}"
ContentStringFormat="{}{0:dd.MM ddd}"/>
<!--Label Grid.Column="1" Content="{Binding Value.FromDate}"
ContentStringFormat="{}{0:HH:mm}"/-->
</Grid>
</DataTemplate>
...
<ItemsControl ItemsSource="{Binding ElementName=thispage,Path=MyDictionary}"
ItemTemplate="{StaticResource Mytemplate}" />
我的班级:
public class MyClass
{
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public string ThisString { get; set; }
public MyClass()
{
...
}
}
【问题讨论】:
-
你在使用 MVVM 吗?如果 MyDictionary 属性的类型为
Dictionary<DataTime, MyClass>,那么您的模板是错误的,因为您将 DataType 指定为x:Type local:MyClass。还有为什么在ItemsSource的绑定中使用ElementName? -
我是。是的,它的类型是
Dictionary<DateTime, MyClass>。提供 Dictionary 作为 DataType 的语法如何? -
我认为这里不需要DataType。如果您删除它,您的绑定应该可以工作。
-
@tzippy 不知道您简化了多少代码,但
FromDate、ToDate和ThisString看起来像公共字段,您无法绑定到字段。这不是有效的binding source。如果是这种情况,您需要通过添加{ get; set; }转换为公共财产,例如 -
@tzippy dkozl 是对的,你必须使用属性来代替......你也可能想看看这个链接:stackoverflow.com/a/2495488/4668080