使用 XAML 为 UserControl 中的所有元素添加前景色设置器
我的用户控件包含许多标签。在 XAML 中,我想定义一个设置器,允许客户端同时设置所有这些的前景。
源代码:(简化)
在Page.Resources下:
<DataTemplate x:Key="customItemTemplate">
<StackPanel Orientation="Horizontal">
<MyControlLib:XYControl Unit="{Binding XYUnit}"/>
<TextBlock Text="{Binding XYMultiplier}" Width="16"/>
</StackPanel>
</DataTemplate>
在页面内容中:(
<ListBox x:Name="XYZList" ItemTemplate="{StaticResource customItemTemplate}">
<!-- Set Foreground to "Red" for all items -->
<!-- For XYControl this is the TextForeground property -->
<!-- For TextBlock this is (naturally) the Foreground property -->
</ListBox>
阅读XAML注释以了解我想要实现的WPF伟大之处)
当然,customItemTemplate
用于页面中不止一处,具有不同的颜色。
在 WPF 中这该多简单啊!
My UserControl contains a number of Labels. In XAML I want to define a setter that allows clients to set the Foreground for all of these at once.
Source code: (simplified)
Under Page.Resources:
<DataTemplate x:Key="customItemTemplate">
<StackPanel Orientation="Horizontal">
<MyControlLib:XYControl Unit="{Binding XYUnit}"/>
<TextBlock Text="{Binding XYMultiplier}" Width="16"/>
</StackPanel>
</DataTemplate>
In Page contents:
<ListBox x:Name="XYZList" ItemTemplate="{StaticResource customItemTemplate}">
<!-- Set Foreground to "Red" for all items -->
<!-- For XYControl this is the TextForeground property -->
<!-- For TextBlock this is (naturally) the Foreground property -->
</ListBox>
(Read the XAML comments for the WPF greatness I want to achieve)
Of course, customItemTemplate
is used in more than one place in the page, with a different color.
How simple could it be in WPF!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望 UserControl 的用户能够在外部设置该值,则可以定义一个新的 DependencyProperty,然后可以在控件的任何实例上设置该值。
然后,您可以在绑定到该值的 UserControl 内为 Label 创建默认样式:
然后,该控件的任何实例都可以设置自己的值,该值将应用于其自己的标签:
If you want the value to be able to be set externally by users of the UserControl, you can define a new
DependencyProperty
, which can then be set on any instance of the control.You can then create a default Style for Label inside the UserControl that binds to this value:
Any instance of the control can then set its own value that will be applied to its own Labels:
我相信这个例子会对你有所帮助。
样式在父节点中定义,因此它对所有标签生效,并且在其后面的代码中被新样式替换。
XAML:
隐藏代码:
I believe this example will help you.
A style is defined in a parent node so it takes effect on all the labels, and in the code behind it's beeing replaced by a new style.
XAML:
Code behind: