当我尝试通过 ResourceDictionary
中的 Setter
设置 WindowStartupLocation
属性时,我得到一个 XamlParseException
:
'Set property 'System.Windows.Setter.Property' threw an exception.' Line number 'x' and line position 'y'.
内部异常是一个ArgumentNullException
:
Value cannot be null. Parameter name: property.
我在资源字典中的风格是:
<Style TargetType="Window" x:Key="WindowStyle">
<Setter Property="SizeToContent" Value="WidthAndHeight" />
<Setter Property="ResizeMode" Value="CanMinimize" />
<Setter Property="WindowStartupLocation" Value="CenterOwner" />
</Style>
问题不在于使用 ResourceDictionary
,因为当我删除 WindowStartupLocation
时,其他两个属性(SizeToContent
和 ResizeMode
) 在引用样式的窗口上按预期设置:
<Window x:Class="WpfApplication1.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Style="{DynamicResource WindowStyle}">
<Window.Resources>
<ResourceDictionary Source="MyResourceDictionary.xaml" />
</Window.Resources>
</Window>
有人遇到过吗?这是 WPF 的错误/限制吗?
附言我知道这个问题类似于 Window Startup Location from resource dictionary , 但在另一个问题中没有提供足够的信息,随后仍未解决。
最佳答案
问题是 WindowStartupLocation 不是 DependencyProperty,因此您不能在样式 setter 中设置它。在 ILSpy 中查看 Setter 调用
CheckValidProperty(DependencyProperty property)
并抛出 NullArgumentException。
由于 WindowStartupLocation 只是一个 CLR 属性,不能以这种方式设置。
但是,您仍然可以使用 ResourceDictionary
:
<Application.Resources>
<ResourceDictionary>
<Style x:Key="WindowStyle" TargetType="Window">
<Setter Property="SizeToContent" Value="WidthAndHeight" />
<Setter Property="ResizeMode" Value="CanMinimize" />
</Style>
<WindowStartupLocation x:Key="WSL">CenterOwner</WindowStartupLocation>
</ResourceDictionary>
</Application.Resources>
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStartupLocation="{StaticResource WSL}"
Style="{StaticResource WindowStyle}" />
关于c# - 从 ResourceDictionary 设置 WindowStartupLocation 会引发 XamlParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10596515/