2013-06-25 33 views
0

我有N個數據點和一個N長度的字符串列表。我想創建一個樣式資源,我可以將它應用於每個將每個TextBlock綁定到列表中的元素的DataPoint。這樣使用一種樣式,將多個對象綁定到列表

<Style TargetType="charting:DataPoint" x:Key="annotatedChart"> 
     <Setter Property="Background" Value="CornflowerBlue"/> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="charting:DataPoint"> 
        <Grid> 
         <Rectangle 
          Fill="{TemplateBinding Background}" 
          Stroke="Black"/> 
         <Grid 
          Background="#aaffffff" 
          Margin="0 -20 0 0" 
          HorizontalAlignment="Center" 
          VerticalAlignment="Top"> 
          <TextBlock 
           x:Name="textBox" 
           Text="{Binding}" <!--TODO --> 
           FontWeight="Bold" 
           Margin="2"/> 
         </Grid> 
        </Grid> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

東西,我需要的文本綁定到一個列表,以便用這種風格的每一個數據點顯示從列表中匹配的文本元素。我曾嘗試將我的主窗口的DataContext設置爲幾個對象和屬性,但都無濟於事。有一次,我的數據點顯示了依賴和獨立的值,但從未列出任何字符串。

+2

好的,你忘了問一個問題。你有嘗試過什麼嗎? – tnw

+0

我已經嘗試了很多東西,似乎讓我無處可尋。它大部分涉及操縱主窗口的DataContext,但它根本沒有幫助。 – sirdank

+0

我不確定你的意思,但看看這個http://www.wpf-tutorial.com/list-controls/itemscontrol/ – Lucas

回答

0

我想通了。我創建了一個獨立值和標籤的字典,將其設置爲我的窗口的DataContext,並使用IValueConverter將文本框綁定到它,從而在字典中查找相關值並將其映射到標籤。

<TextBlock 
      x:Name="textBox" 
      Text="{Binding Key, Converter={StaticResource annotationsConverter}}" 
      FontWeight="Bold" 
      Margin="2" 
      TextWrapping="Wrap"/> 

public class myAnnotationsConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (MainWindow.annotations != null) 
     { 
      try 
      { 
       return MainWindow.annotations[value as string]; 
      } 
      catch (KeyNotFoundException e) 
      { 
       return "NULL"; 
      } 

     } 
     throw new NotFiniteNumberException(); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotFiniteNumberException(); 
    } 
} 

可能的改進:支持每個類別一個以上的列在類別軸。所以,如果我在2007年6月有三個酒吧,爲所有人保留一個獨特的標籤。

相關問題