在某些情况下,我遇到的问题是我在WPF窗口上设置的FontSize
没有继承到子控件。
如果自定义用户控件在更改Label
时设置其内容(例如DataContext
),则会发生这种情况。
我可以在将此UserControl
放入新窗口时重现此操作,然后关闭此窗口并创建一个新窗口,其中包含相同的UserControl
(请参阅以下代码)。
在我的复杂应用程序中,它是一个自定义弹出窗口和一个自定义UserControl
,如果DataContext
发生更改,它会更改其内容。在窗口的第一次打开时,字体不会被继承(因此用户控件在此之前不在另一个可视/逻辑树中),但我无法在小型测试应用程序中重现这一点。
public partial class App : Application
{
// App.xaml: ShutdownMode="OnExplicitShutdown"
private void Application_Startup(object sender, StartupEventArgs e)
{
var testControl = new TestControl();
var w = new Window();
w.FontSize = 40;
w.DataContext = this;
w.Content = testControl; // TestControl.DataContextChanged creates label which has FontSize = 40
w.Show();
w.Close();
w.DataContext = null;
//w.Content = null; // if this is done, the font will be correct (40)
w = null;
w = new Window();
w.FontSize = 40;
w.DataContext = this;
//testControl.DataContext = this; // if this is done, the font will be correct (40)
w.Content = testControl; // TestControl.DataContextChanged creates label with remaining FontSize = 12 (Default)
w.Show();
}
}
public class TestControl : UserControl
{
public TestControl()
{
DataContextChanged += TestControl_DataContextChanged;
}
private void TestControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != null) Content = new Label() { Content = "TestControllabel"};
else Content = null;
}
}
我不是在寻找这个示例应用程序的修复程序,但由于为什么的原因,在这种特殊情况下不会继承字体大小,所以也许我可以修复我的复杂应用程序。 任何想法都会有用!
编辑:现在我通过设置控件的datacontext来修复我的应用程序,然后再将其设置为窗口内容。