我有一个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>
Run Code Online (Sandbox Code Playgroud)
以下是使用该样式的ListBox控件之一的示例:
<ListBox x:Name="lbCampaigns" Button.Click="lbCampaigns_Click" ItemsSource="{Binding}" Style="{StaticResource listBox}" />
Run Code Online (Sandbox Code Playgroud)
如何在父ListBox中设置Button控件的内容(btnGet)?
我知道我希望按钮在设计时为Window上的每个ListBox显示什么文本.(即我不需要将它绑定到ListBox ItemsSource).我看到我可以定义子控件的事件(请参阅Button.Click定义),但似乎我不能以相同的方式设置子控件的属性.
有任何想法吗?谢谢!
您的设置Button.Click不是将事件处理程序分配给Button.它正在分配给它ListBox.它的工作原理是因为WPF的路由事件系统.
如果你想要Button在一个级别上设置一个值ListBox,在这种情况下,一个选项是使用Bindinga RelativeSource:
<Button Content="{Binding Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"/>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我刚刚劫持了该Tag属性,您可以指定如下:
<ListBox Tag="This is the button's content" .../>
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用继承的附加属性.例如:
<Button Content="{Binding local:MyClass.MyAttachedProperty}"/>
Run Code Online (Sandbox Code Playgroud)
然后:
<ListBox local:MyClass.MyAttachedProperty="This is the button's content"/>
Run Code Online (Sandbox Code Playgroud)
最后,如果你正在模仿它ListBox自己,你可以"伸出"并绑定到你正在模板化的控件的属性TemplateBinding:
<Button Content="{TemplateBinding Tag}"/>
Run Code Online (Sandbox Code Playgroud)
当然,这种技术通常与模板化控件上专门声明的属性一起使用.例如,您可以继承ListBox并添加自己的ButtonContent属性.然后,在您的模板中,您可以伸出并绑定到该属性Button.