Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 从父控件设置WPF嵌套控件属性_.net_Wpf_Xaml - Fatal编程技术网

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

.net 从父控件设置WPF嵌套控件属性,.net,wpf,xaml,.net,Wpf,Xaml,我有一个WPF窗口,上面有多个ListBox控件,所有这些控件都共享我在这里简化的相同样式: <Style x:Key="listBox" TargetType="{x:Type ListBox}"> <Setter Property="ItemTemplate"> <Setter.Value> <DataTemplate> <

我有一个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}" />

如何在父列表框中设置按钮控件(btnGet)的内容

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

有什么想法吗?
谢谢

您对
按钮的设置。单击
不会将事件处理程序分配给按钮。它正在将其分配给
列表框
。它之所以能够工作,是因为WPF的路由事件系统

如果希望
按钮
采用在
列表框
级别设置的值,这种情况下的一个选项是将
绑定
相对资源

<Button Content="{Binding Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"/>
另一种选择是使用继承的附着属性。例如:

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

当然,这种技术通常与模板控件上专门声明的属性一起使用。例如,您可以将
列表框
子类化,并添加自己的
按钮内容
属性。然后,在模板中,您可以通过
按钮

访问并绑定到该属性。嗨,肯特,谢谢您的帮助。您的FindAncestor代码段中是否有输入错误?当我将其复制粘贴到我的按钮内容属性中时,我得到一个“必须在FindAncestor模式下为RelativeSource指定AncestorType。”错误。我会继续查找,但我想我会提到它,以防您能提供更多帮助。:)呸,看起来像是VisualStudio错误。我重新构建了解决方案,错误消失了!感谢您的帮助。是的,这是使用相对资源粘贴绑定时的常见错误。我一直都有。@Scott:不客气。我只是对我的帖子做了一些编辑,使它更清晰、更全面。
<Button Content="{Binding local:MyClass.MyAttachedProperty}"/>
<ListBox local:MyClass.MyAttachedProperty="This is the button's content"/>
<Button Content="{TemplateBinding Tag}"/>