按事件处理程序更改窗口属性

时间:2018-02-12 14:31:32

标签: wpf

我需要根据事件处理程序更改 Window 的属性(例如背景颜色)。 我们可以通过在windows.Resources中编写它来轻松地对窗口内的任何控件执行此操作,如下所示。

<Window x:Class="WpfApplication8.Window1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication8"
             mc:Ignorable="d" 
            >
    <Window.Resources>
        <ResourceDictionary>
            <Style TargetType="{x:Type Button}" >
                <EventSetter Event="SizeChanged" Handler="OnbuttonLoaded"/>
            </Style>
        </ResourceDictionary>
    </Window.Resources>
        <StackPanel>
            <Button x:Name="Button1" Width="100" Height="20"/>
            <Button Width="100" Height="20"/>
            <Button Width="100" Height="20"/>
            <Button Width="100" Height="20"/>
            <Button Width="100" Height="20"/>
        </StackPanel>
</window>

xaml.cs如下

 private void OnbuttonLoaded(object sender, RoutedEventArgs e)
        {
            Button1.Background = Brushes.Red;
        }

但是当我需要更改窗口的背景颜色时,它的SizeChanged。我能做什么??? 请帮忙......谢谢

1 个答案:

答案 0 :(得分:0)

为什么不使用Window Style属性?

<Window.Style>
    <Style TargetType="{x:Type Window}">
        <EventSetter Event="SizeChanged" Handler="EventSetter_OnHandler"/>
    </Style>
</Window.Style>

如果您需要一些全球解决方案,请将其放入App Resources。

相关问题