Window Startup Location from resource dictionary

孤街醉人 提交于 2019-12-10 10:34:49

问题


I'm trying to set all my windows to open in the center of the screen. All my windows use style file:

    <Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Styles/Mystyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>

So I just inserted this property to the resource dictionary:

    <Style x:Key="windowStyle" TargetType="Window">
         <Setter Property="WindowStartupLocation" Value="CenterScreen"/>
    </Style> 

But, it doesn't work. Am I missing something?


回答1:


You cannot use a Style to define WindowStartupLocation, this is due to the fact that it is not a dependency property. You can define a StaticResource in your resource dictionary which you will use in your windows:

<WindowStartupLocation x:Key="StartupLocation">CenterScreen</WindowStartupLocation>

and then use it like so:

WindowStartupLocation="{DynamicResource StartupLocation}"



回答2:


You don't need to use x:Key attribute. Your style must look like this:

<Style TargetType="{x:Type Window}">
    <Setter Property="WindowStartupLocation" Value="CenterScreen"/>
</Style> 



回答3:


if you dont want to use implicit styles (as bniwredyc suggested) you must set style explicitly:

<Window **Style="{StaticResource windowStyle}"**>
<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../Styles/Mystyles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Window.Resources>



回答4:


To make every start every window at Center Screen Add this line in App.xaml

<Application.Resources>
        <WindowStartupLocation x:Key="StartupLocation">CenterScreen</WindowStartupLocation>
</Application.Resources>

and add this line in Window tag

WindowStartupLocation="{StaticResource StartupLocation}"


来源:https://stackoverflow.com/questions/9976097/window-startup-location-from-resource-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!