我有一个自定义样式的WPF窗口:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" AllowsTransparency="True" WindowStyle="None" Width="525" Style="{DynamicResource CustomWindowStyle}">
<Window.Resources>
<Style x:Key="CustomWindowStyle" TargetType="{x:Type Window}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border BorderBrush="Black" BorderThickness="7" Background="{x:Null}" MouseMove="WindowMouseMove" MouseDown="WindowMouseDown">
<Grid Background="Transparent" DockPanel.Dock="Top">
<!--WPF Control of interest-->
<Border x:Name="BORDERCONTROL" HorizontalAlignment="Left" Margin="10,10,0,0" Width="20" Height="20" Background="Black" />
<AdornerDecorator>
<ContentPresenter/>
</AdornerDecorator>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
</Grid>
我想以编程方式更改BORDERCONTROL背景:
private void ChangeBackground()
{
BORDERCONTROL.Background = Brushes.Yellow;
}
但是我无法使用此方法访问此控件。
是否有一种简单的方法可以从代码隐藏中更改位于控件模板中的控件属性?
感谢您的帮助。
答案 0 :(得分:1)
试试这个:
var bor = (Border)Template.FindName("BORDERCONTROL", this);
bor.Background = Brushes.Yellow;
答案 1 :(得分:1)
private void Button_Click(object sender, RoutedEventArgs e)
{
Border b = (Border)this.Template.FindName("BORDERCONTROL", this);
b.Background = new SolidColorBrush(Colors.Yellow);
}
这将为您提供所需的边框控件,并更改其颜色。但是不要试图在Window Constructor中访问Border,因为它总是为null。
答案 2 :(得分:0)
如果您使用TemplateBinding
,则可以绑定到Window的Background
属性并更改:
<Style x:Key="CustomWindowStyle" TargetType="{x:Type Window}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border BorderBrush="Black" BorderThickness="7" Background="{x:Null}"
MouseMove="WindowMouseMove" MouseDown="WindowMouseDown">
<Grid Background="Transparent" DockPanel.Dock="Top">
<!--WPF Control of interest-->
<Border x:Name="BORDERCONTROL" HorizontalAlignment="Left"
Margin="10,10,0,0" Width="20" Height="20"
Background="{TemplateBinding Background}" />
<AdornerDecorator>
<ContentPresenter/>
</AdornerDecorator>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
private void ChangeBackground()
{
myWindow.Background = Brushes.Yellow;
}