代码之家  ›  专栏  ›  技术社区  ›  Scott Ferguson

从父控件设置WPF嵌套控件属性

  •  4
  • Scott Ferguson  · 技术社区  · 17 年前

    我有一个WPF窗口,上面有多个列表框控件,它们共享我在这里简化的相同样式:

       <Style x:Key="listBox" TargetType="{x:Type ListBox}">
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Border BorderBrush="Black">
                            <StackPanel Orientation="Horizontal" >
                                <TextBlock Text="{Binding Path=name}" />
                                <TextBlock Text="{Binding Path=text}" />
                                <TextBlock Text="id:" />
                                <TextBlock x:Name="_idTextBlock" Text="{Binding Path=id}" />
                                <Button Name="btnGet" CommandParameter="{Binding Path=id}" />
                            </StackPanel>
                        </Border>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    

    下面是一个使用该样式的列表框控件的示例:

    <ListBox x:Name="lbCampaigns" Button.Click="lbCampaigns_Click" ItemsSource="{Binding}" Style="{StaticResource listBox}" />
    

    如何从父列表框中设置按钮控件(btnget)的内容?

    我知道我希望按钮在设计时为窗口上的每个列表框显示什么文本。(即,我不需要将其绑定到列表框项源)。我看到我可以定义子控件的事件(请参见按钮。单击定义),但看起来我不能以相同的方式设置子控件的属性。

    有什么想法吗? 谢谢!

    1 回复  |  直到 15 年前
        1
  •  8
  •   Tim Cooper    15 年前

    你的设置 Button.Click 未将事件处理程序分配给按钮。它分配给 ListBox . 它的工作是因为WPF的路由事件系统。

    如果你想要 Button 在 列表框 ,在这种情况下,一个选项是使用 Binding 用一个 RelativeSource :

    <Button Content="{Binding Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"/>
    

    在这种情况下,我刚刚劫持了 Tag 属性,可以指定如下:

    <ListBox Tag="This is the button's content" .../>
    

    另一个选项是使用继承的附加属性。例如:

    <Button Content="{Binding local:MyClass.MyAttachedProperty}"/>
    

    然后:

    <ListBox local:MyClass.MyAttachedProperty="This is the button's content"/>
    

    最后,如果你正在模板化 列表框 本身,您可以使用 TemplateBinding :

    <Button Content="{TemplateBinding Tag}"/>
    

    当然,此技术通常与模板化控件上特别声明的属性一起使用。例如,您可以子类 列表框 加上你自己的 ButtonContent 财产。然后,在模板中,您可以从 纽扣 .