按钮单击Wpf时更改ControlTemplate

时间:2017-12-29 18:48:07

标签: python wpf visual-studio xaml mvvm

我有以下简单的XAML文件:

<Window 
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       Title="WpfApplication4" Height="300" Width="300">
    <Window.Resources>
        <ControlTemplate x:Key="simpleErrorTemplate">
            <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T1" />
        </ControlTemplate>
        <ControlTemplate x:Key="detailedErrorTemplate">
            <StackPanel>
                <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T2" />
                <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T3" />
                <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T4" />
            </StackPanel>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl>
            <ContentControl.Style>
                <Style TargetType="ContentControl">
                    <Setter Property="Template"
                        Value="{StaticResource simpleErrorTemplate}"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=Button,Path=IsPressed}" Value="True">
                            <Setter Property="Template" Value="{StaticResource detailedErrorTemplate}"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ContentControl.Style>
        </ContentControl>
        <Button x:Name="Button" Content="Button" Height="40" Width="129" Margin="88,5,76,5" Grid.Row="1" Click="Button_Click1"/>
    </Grid>
</Window>

它的作用是在按下按钮时更改模板。 但是,我希望它在我点击后发生,而不需要按住它。

1)点击样式是否有任何触发器,所以当我点击它时会调用触发器?

2)在代码隐藏文件中,我喜欢它在我单击按钮时运行一个函数,然后才更改模板,因为它使用的是第一个模板中的数据。

import wpf

from System.Windows import Application, Window
from scores import score

class MyWindow(Window):
    def __init__(self):
        self.ui = wpf.LoadComponent(self, 'WpfApplication1.xaml')

    def Button_Click1(self, sender, e):
        x = score(name)

if __name__ == '__main__':
    Application().Run(MyWindow())

所以最终我的目标是点击按钮,计算功能得分,然后再更改模板。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在MyWindow中定义DependencyProperty:(MyWindow.xaml.cs)

    public bool MyBoolean
    {
        get { return (bool)GetValue(MyBooleanProperty); }
        set { SetValue(MyBooleanProperty, value); }
    }
    public static readonly DependencyProperty MyBooleanProperty =
        DependencyProperty.Register("MyBoolean", typeof(bool), typeof(MyWindow), new PropertyMetadata(false));

单击该按钮时,此布尔必须设置为true。

然后命名你的MyWindow:

<Window x:Name="root"
        .../>

然后你的触发器就像:

<DataTrigger Binding="{Binding ElementName=root,Path=MyBoolean}" Value="True">
    <Setter Property="Template" Value="{StaticResource detailedErrorTemplate}"/>
</DataTrigger>
相关问题