0

我有一个ListBox根据用户设置的整数属性添加项目数的地方。这些项目是从ControlTemplate由标签和TextBox内部组成的资源创建的DockPanel。标签不是数据绑定的,但我希望它具有基于ListboxItem它所包含的 (index + 1) 的某种动态内容。我的问题/问题是我希望能够更新每个标签的内容ListboxItem,但由于某种原因无法访问标签。我不知道有任何方法可以通过标签的数据绑定来做到这一点,因为标签在模板中并且不知道它的父级是ListboxItem. 任何人都可以帮助我消除其中的一些困惑,让我回到正确的轨道上吗?

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

我希望能够绑定Labelxaml中的内容,或者更新Label后面代码中的内容。我不确定最好的路线是什么。

4

2 回答 2

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>
于 2008-12-04T00:13:53.597 回答
0

更新:最初我试图Label在模板中找到这样的....

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

我发现您必须先调用ApplyTemplate()才能构建模板的可视化树,然后才能找到该元素。

于 2008-12-03T17:17:59.207 回答