【发布时间】:2020-06-21 22:18:32
【问题描述】:
我在运行时遇到了 Visual Studio 异常,但我不知道它是从哪里来的!
我正在 WPF 中创建食谱书和膳食计划器桌面应用程序。我目前正在开发允许用户在食谱中输入成分的界面。
我对每个单独的成分都有一个用户控件,我将其动态添加到配方用户控件的堆栈面板中。堆栈面板使用以下代码包装在 ScrollViewer 中:
<ScrollViewer Grid.Row="3" VerticalScrollBarVisibility="Auto" Margin="20,10,0,0">
<StackPanel Name="IngredientsPanel">
<!--IngredientUserControl objects are dynamically added here-->
</StackPanel>
</ScrollViewer>
添加成分一直有效,直到成分填满堆栈面板中的可见空间。那时,我没有出现滚动条,而是出现以下异常:
System.Windows.Markup.XamlParseException: ''{DependencyProperty.UnsetValue}' is not a valid value for
property 'Foreground'.'
This exception was originally thrown at this call stack:
[External Code]
我怀疑这是我为在成分用户控件中设置文本框和文本块格式而定义的一些样式的问题。我将这些样式保存在我的 App.xaml 文件中包含的 Fonts.xaml 资源字典中。我的字体样式大致是这样的:
<!--Body1 text (used for static large body text)-->
<Style x:Key = "Body1Text" TargetType = "TextBlock">
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="TextAlignment" Value="Left"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Foreground" Value="{DynamicResource PrimaryBrush}"/>
<Setter Property="FontFamily" Value="Comic Sans MS"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Margin" Value="5"/>
</Style>
PrimaryBrush 是一个 SolidColorBrush,我在所有用户控件的资源部分中对它进行了不同的定义(我这样做是因为颜色主题在我的应用程序的不同组件中有所不同,但字体样式却没有)。例如,在我的 IngredientUserControl 中,我有以下资源:
<UserControl.Resources>
<SolidColorBrush x:Key="PrimaryBrush" Color="{StaticResource OrangeTheme}"></SolidColorBrush>
<SolidColorBrush x:Key="AccentBrush" Color="{StaticResource LightTealTheme}"></SolidColorBrush>
</UserControl.Resources>
还有这个文本块:
<TextBlock Name="Quantity" Margin="0,20,0,5"
Text="{Binding Path=Quantity, Mode=OneWay}"
Style="{StaticResource Body1Text}">
</TextBlock>
所有样式都可以正常工作和显示,直到成分面板空间不足! 当 ScrollViewer 填满时,它会中断并且无法再在某处找到某些前景属性。我不明白为什么只有在 ScrollViewer 需要滚动时才会出现这个问题。有什么想法吗?
【问题讨论】:
-
如何将
TextBlocks 添加到StackPanel? -
@Rekshino 这个问题已经提供了足够的信息来回答而不引用规则。 XAML 依赖路径完全在那里,发帖人已经解释了发生错误的具体情况。我觉得我的回答解释了一个很好的查询线来找到解决方案,所以我很困惑有人在没有添加或建议改进的情况下否决了它。
-
@Kodaloid,你的回答好像消失了,但是很有帮助,谢谢!
-
看来版主删除了我的答案,无论如何我很高兴你找到了解决方案!
标签: wpf dependency-properties scrollviewer dynamicresource