tags:

views:

27

answers:

1

Hi I have in xaml as following:

<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>

This will create a label on the right side and a combo box on the right side. The Itemssource for combo box will come from the code as:

ColorCombo.ItemsSource = ColorsDictionary;

Here colorsdictionary is defined as:

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

But now, i am trying to add combo and the entire Itemtemplate through code. But I am not getting how to do( bind the data) through code, anyone can help me out?

Thanks & Regards

Padma

A: 

To answer you question you can create a Binding programatically like this:-

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

However that isn't actually that useful to you.

The DataTemplate cannot be created in code in the manner above. The only way to build a DataTemplate programmatically is to create a Xaml string (perhaps with the aid of XDocument) and then use XamlReader to load the generated Xaml. Are you really sure you need to do all this programmatically?

AnthonyWJones
Yes i need to do all these programmatically.Let's say if i need not to do so, Can you tell me how to refer the Datatemplate defined in the Xaml in Code behind? I am not able to access resources defined in the App/xaml
padmavathi
@padmavathi: I'm not sure I understand your supplementary question, you can access the `DataTemplate` in your Xaml with `ColorCombo.ItemsTemplate` but I don't think that helps you.
AnthonyWJones