2008-12-03 119 views
0

標籤我有一個ListBox其中基於與整數屬性由用戶設置添加的項目數。該項目是從一個ControlTemplate的資源,其中包括一個標籤和一個TextBox一個DockPanel的內部創建的。該標籤是未綁定數據,但我想使其具有基於用於包含它的ListboxItem的(索引+ 1)稍微動態內容。我的問題是,我希望能夠更新每個ListboxItem的標籤內容,但由於某種原因無法訪問標籤。我不知道有什麼辦法通過數據綁定的標籤,因爲標籤是在一個模板,並不知道它有一個家長是一個ListboxItem做到這一點。任何人都可以幫我澄清一些這些混亂讓我回到正確的軌道嗎?WPF:更新列表框項

<ControlTemplate TargetType="{x:Type ListBoxItem}"> 
    <DockPanel Background="Transparent" Height="28" Name="playerDockPanel" VerticalAlignment="Bottom"> 
     <Label Name="playerNameLabel" DockPanel.Dock="Left" Content="Player"></Label> 
     <TextBox Height="23" Width ="150" Name="playerName" DockPanel.Dock="Right"/> 
    </DockPanel> 
</ControlTemplate> 

我希望能夠在Label的內容Label的內容綁定在XAML,或更新的代碼後面。我不確定最好的路線是什麼。

回答

0

UPDATE:最初我是想找到這樣的模板Label ....

Label label = (Label)lbi.Template.FindName("playerNameLabel",lbi); 

我發現你必須調用ApplyTemplate()爲了前,將建立模板的可視化樹能夠找到元素。

0

你必須創建一個IMultiValueConverter,將讓您的模板的索引:

public class PositionConverter : IMultiValueConverter 
{ 
    public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture) 
    { 
     ItemsControl itemsControl = value[0] as ItemsControl; 
     UIElement templateRoot = value[1] as UIElement; 
     if (templateRoot != null) 
     { 
      UIElement container = ItemsControl.ContainerFromElement(itemsControl, templateRoot) as UIElement; 
      if (container != null) 
      { 
       return itemsControl.ItemContainerGenerator.IndexFromContainer(container); 
      } 
     } 

     return null; 
    } 

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

你應該再使用轉換器轉換成你的DataTemplate

<DataTemplate x:Key="itemTemplate"> 
    <DockPanel Background="Transparent" Height="28" Name="playerDockPanel" VerticalAlignment="Bottom"> 
     <Label Name="playerNameLabel" DockPanel.Dock="Left" Content="{Binding Title}"></Label> 
     <Label Height="23" Width ="150" Name="playerName" DockPanel.Dock="Right"> 
      <Label.Content> 
       <MultiBinding Converter="{StaticResource positionConverter}"> 
        <!-- The ItemsControl--> 
        <Binding ElementName="listBox" /> 
        <!-- The root UIElement--> 
        <Binding ElementName="playerDockPanel"/> 
       </MultiBinding> 
      </Label.Content>      
     </Label> 
    </DockPanel> 
</DataTemplate>