如何通过代码使用DataBinding?

时间:2010-08-03 09:11:17

标签: silverlight

我在xaml中有以下内容:

<StackPanel Orientation="Horizontal" Margin="0 5 0 0" HorizontalAlignment="Center" VerticalAlignment="Bottom">
 <TextBox Text="LinkColor" VerticalAlignment="Center"  IsReadOnly="True"/>
 <ComboBox x:Name="ColorCombo" MinWidth="180" Margin="5 0 0 0" SelectionChanged="ColorCombo_SelectionChanged">
 <ComboBox.ItemTemplate>
  <DataTemplate>
    <StackPanel Orientation="Horizontal">
       <Rectangle Fill="{Binding Key}" VerticalAlignment="Center" Height="10" Width="20"/>
          <TextBlock Text="{Binding Key}" Margin="5 0 0 0" VerticalAlignment="Center" />
    </StackPanel>
  </DataTemplate>
 </ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>

这将在右侧创建一个标签,在右侧创建一个组合框。 Itemssource for combo框将来自代码:

ColorCombo.ItemsSource = ColorsDictionary;

这里colorsdictionary被定义为:

Dictionary<string, Color> ColorsDictionary = new Dictionary<string, Color>();

但是现在,我正在尝试通过代码添加组合和整个Itemtemplate。但是我没有通过代码得到怎么做(绑定数据),任何人都可以帮助我?

1 个答案:

答案 0 :(得分:0)

要回答你的问题,你可以像这样以编程方式创建Binding: -

 TextBlock tb = new TextBlock;
 tb.SetBinding(TextBlock.TextProperty, new Binding("Key"));

然而,这实际上对您没有用。

无法以上述方式在代码中创建DataTemplate。以编程方式构建DataTemplate的唯一方法是创建一个Xaml字符串(可能借助XDocument),然后使用XamlReader加载生成的Xaml。你真的确定你需要以编程方式完成所有这些吗?