2008-12-03 121 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>