Silverlight 如何通过代码隐藏使用数据绑定?

Silverlight 如何通过代码隐藏使用数据绑定?,silverlight,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" MinW

我在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>
此处,colorsdictionary的定义如下:

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

但现在,我试图通过代码添加combo和整个Itemtemplate。但我不知道如何通过代码(绑定数据),任何人都可以帮助我吗?

要回答您的问题,您可以通过编程方式创建一个
绑定,如下所示:-

 TextBlock tb = new TextBlock;
 tb.SetBinding(TextBlock.TextProperty, new Binding("Key"));
然而,这实际上对你没有多大用处


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

欢迎使用SO,请花几分钟时间阅读常见问题解答和降价文档(编辑问题时,右边空白处有一个有用的语法)。是的,我需要以编程方式完成所有这些工作。假设我不需要这样做,您能告诉我如何在代码隐藏中引用Xaml中定义的数据模板吗?我无法访问应用中定义的资源/xaml@padmavathi:我不确定我是否理解您的补充问题,您可以使用
ColorCombo.ItemsTemplate
访问Xaml中的
DataTemplate
,但我认为这对您没有帮助。
 TextBlock tb = new TextBlock;
 tb.SetBinding(TextBlock.TextProperty, new Binding("Key"));