2010-08-03 61 views
1

我在XAML如下:如何通過後面的代碼使用DataBinding?

<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爲組合框將來自代碼:

ColorCombo.ItemsSource = ColorsDictionary; 

這裏colorsdictionary被定義爲:

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

但現在,我試圖通過代碼來添加組合和整個的ItemTemplate。但是我不知道如何通過代碼來實現(綁定數據),任何人都可以幫助我?

+0

歡迎來到SO,請花幾分鐘時間閱讀常見問題解答和Markdown文檔(在編輯問題時可在右側空白處找到有用的synposis)。 – AnthonyWJones 2010-08-03 09:27:03

回答

0

要回答你的問題,你可以創建一個Binding編程方式是這樣的: -

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

但是實際上不是對你有用。

無法按上述方式在代碼中創建DataTemplate。以編程方式構建DataTemplate的唯一方法是創建一個Xaml字符串(可能需要藉助XDocument),然後使用XamlReader加載生成的Xaml。你真的確定你需要以編程方式完成所有這些嗎?

+0

是的,我需要以編程方式完成所有這些。 讓我們說如果我不需要這樣做,你能告訴我如何引用代碼中Xaml中定義的數據模板?我無法訪問App/xaml – padmavathi 2010-08-03 09:52:21

+0

@padmavathi中定義的資源:我不確定我是否理解您的補充問題,您可以使用'ColorCombo.ItemsTemplate'訪問Xaml中的'DataTemplate',但我不認爲這可以幫助你。 – AnthonyWJones 2010-08-03 14:33:38