对于我的自定义控件,我正在使用动态资源来设置 Foreground 属性。最初,当我运行应用程序时,前景属性未设置为我的控件。当我动态更改值时,前景已正确应用。如何解决此问题?
PS:简单的示例 Wpf应用程序4
MainWindow.xaml
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Width="300"
Height="200">
<Window.Resources>
<SolidColorBrush x:Key="ForegroundBrush" Color="Red" />
<SolidColorBrush x:Key="BackgroundBrush" Color="Yellow" />
<Style x:Key="MyStyle" TargetType="ContentControl">
<Setter Property="Foreground" Value="{DynamicResource ForegroundBrush}" />
<Setter Property="Background" Value="{DynamicResource BackgroundBrush}" />
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel>
<Button Click="ButtonBase_OnClick" Content="Create and Add Custom Control With Style" />
<Button Click="ButtonBase_OnClick_1" Content="Change Color" />
</StackPanel>
<StackPanel x:Name="myPanel" Grid.Row="1" />
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var control = new MyControl {Style = this.Resources["MyStyle"] as Style};
control.CreateContent(string.Format("My Control {0}", myPanel.Children.Count + 1));
myPanel.Children.Add(control);
}
private void ButtonBase_OnClick_1(object sender, RoutedEventArgs e)
{
var brush = (SolidColorBrush)Resources["ForegroundBrush"];
Resources["ForegroundBrush"] = new SolidColorBrush(Color.Add(brush.Color, Color.FromRgb(0, 100, 100)));
var brush1 = (SolidColorBrush)Resources["BackgroundBrush"];
Resources["BackgroundBrush"] = new SolidColorBrush(Color.Add(brush1.Color, Color.FromRgb(0, 100, 100)));
}
}
public class MyControl : ContentControl
{
public MyControl()
{
DefaultStyleKey = typeof(MyControl);
}
public void CreateContent(string text)
{
this.Content = new TextBlock() {Text = text};
}
}
通用.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4">
<Style TargetType="local:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyControl">
<Border Background="{TemplateBinding Background}">
<ContentPresenter Content="{TemplateBinding Content}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
如果要将Style
应用于控件,则必须将Style
应用于该控件(在提供的代码示例中尚未执行此操作)。你在这里有两个选择...请尝试以下操作(无论在哪里使用该控件):
<local:MyControl Style="{StaticResource MyStyle}" />
或者像这样定义Style
,这将影响范围内控件的所有实例:
<Style TargetType="ContentControl">
<Setter Property="Foreground" Value="{DynamicResource ForegroundBrush}" />
<Setter Property="Background" Value="{DynamicResource BackgroundBrush}" />
</Style>