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

5

我有一个WPF窗口,上面有多个ListBox控件,它们都共享同一个样式,这里我简化了样式:

   <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 控件示例:

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

如何在父ListBox内设置按钮控件(btnGet)的内容?

我知道我想要每个窗口上的ListBox在设计时显示的按钮文本。(即,我不需要将其绑定到ListBox的ItemsSource)。我可以定义子控件的事件(请参阅Button.Click定义),但似乎无法以相同的方式设置子控件的属性。

有什么建议吗? 谢谢!

1个回答

9

你设置的 Button.Click 并没有将事件处理程序分配给 Button,而是分配给了 ListBox。这是因为 WPF 的路由事件系统起作用了。

如果你希望 Button 接受在 ListBox 级别设置的值,一个选项是在此情况下使用具有 RelativeSourceBinding

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

最后,如果你正在为ListBox本身进行模板化,你可以使用TemplateBinding“接触”并绑定到你正在模板化的控件的属性:

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

当然,这种技术通常与在模板控件上特别声明的属性一起使用。例如,您可以对ListBox进行子类化并添加自己的ButtonContent属性。然后,在您的模板中,您可以从Button绑定到该属性。


嗨,肯特,感谢你的帮助。你的FindAncestor代码片段中是否有错别字? 当我将其复制粘贴到我的按钮内容属性中时,会出现“必须为FindAncestor模式中的RelativeSource指定AncestorType”错误。 我会继续寻找,但想提一下,以防你能提供更多帮助。 :) - Scott Ferguson
噢,看起来是VisualStudio的错误。我进行了解决方案重建,错误消失了!感谢您的帮助。 - Scott Ferguson
是的,当使用RelativeSource粘贴绑定时,这是一个常见的错误。我经常遇到这种情况。 - Denis Troller
@Scott:不用谢。我刚刚对我的帖子进行了一些编辑,使其更加清晰和全面。 - Kent Boogaart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接