对于我的自定义控件,我使用 Dynamic 资源来设置 Foreground 属性。最初,当我运行应用程序时,Foreground 属性未设置为我的控件。当我动态更改值时,前景被正确应用。我该如何解决这个问题?
PS:简单示例WpfApplication4
主窗口.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>
主窗口.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>