在运行时设置ItemsControl DataTemplate绑定字段

时间:2015-10-14 11:09:04

标签: wpf datatemplate itemscontrol

我有这个XAML:

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:Column YControl="{Binding YData}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

如何在运行时使用字符串设置YData变量名称?

1 个答案:

答案 0 :(得分:1)

您可以在C#中动态创建绑定:

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:Column Initialized="SetYControlBinding_OnColumnInitialized"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

代码背后:

void SetYControlBinding_OnColumnInitialized(object sender, EventArgs e)
{
   var control = (Column)sender;
   var binding = ...
   control.SetBinding(Column.YControlProperty, binding);
}