【发布时间】:2016-10-13 08:31:36
【问题描述】:
我有一个带有 UserControl 的 MainWindow。我想更改 UserControl 中的 ListBox 的背景。但 Style 仅适用于 UserControl,而不适用于内部 Control。
稍后我想从外部修改 ListBoxItems..
主窗口
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="279.716" Width="279.784"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
</Window.Resources>
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type local:UserControl1}">
<Setter Property="Background" Value="Black"></Setter>
<Style.Resources>
<Style TargetType="{x:Type ListBox}">
<Setter Property="Background" Value="Red"></Setter>
</Style>
</Style.Resources>
</Style>
</Grid.Resources>
<local:UserControl1 Margin="47,22,34,46"></local:UserControl1>
</Grid>
XAML
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<ListBox Background="Aqua" x:Name="listBox" HorizontalAlignment="Left" Height="192" Margin="54,44,0,0" VerticalAlignment="Top" Width="192"/>
</Grid>
【问题讨论】:
-
本地值 (
<ListBox Background="Aqua" ...) 的优先级高于样式设置器值 -
@ASh 谢谢!这就是问题。有没有办法拥有另一个“初始值”并有可能覆盖它?
-
在
UserControl1中创建一个具有所需默认值的Brush类型的特殊DependencyPropery,并使用TemplateBinding 将ListBox Background绑定到该属性。它应该可以工作,并且您不需要 UserControl1.Resources 中 ListBox 的样式,因为它可以通过样式设置器直接设置 -
..当我想更改 ListBoxItems 的背景时? Collection 绑定到我父窗口上的 UserControl,我想通过属性值修改这些项目。我不想在 UserControl 的 XAML 代码中编写这些触发器,因为我想将其用作通用控件。
-
ListBox 具有 ItemContainerStyle 属性,用于设置其 ListBoxItems 的样式。在 UserControl1 中公开该属性并在 xaml 中使用它会很方便,但我不确定哪种方法是最好的方法。试试看什么是
AddOwner方法并在 ItemContainerStyle 属性上使用它
标签: c# wpf xaml user-controls