EventTrigger赋值属性(无故事板)

时间:2013-07-08 15:56:08

标签: .net wpf eventtrigger

使用某些故事板的事件触发器 还需要为没有故事板的TextBlock指定Opacity 如何根据触发器直接指定值?

<Expander.Triggers>
   <EventTrigger RoutedEvent="Expander.Expanded">

尝试在Expanded事件中执行此操作,但这不起作用。

1 个答案:

答案 0 :(得分:1)

以下是DataTemplate的一个小例子。有一个Grid,其中Expander有两个TextBlocks。一个在扩展器InnerTextBlock内,另一个不在 - OuterTextBlock。当属性IsExpanded == True时,我们会使用DataTriggers执行特定操作。

XAML

<Window.Resources>
    <DataTemplate DataType="{x:Type local:MyExpanderData}">
        <Grid x:Name="MainGrid">
            <Expander Name="MyExpander" Header="{Binding HeaderName}" IsExpanded="{Binding isExpanded}">
                <TextBlock Name="InnerTextBlock" Text="InnerTextBlock" Width="150" Height="30" VerticalAlignment="Top" FontSize="16" />
            </Expander>

            <TextBlock Name="OuterTextBlock" Text="OuterTextBlock" Width="150" Height="30" Margin="0,30,0,0" FontSize="16" />
        </Grid>

        <!-- Our DataTriggers -->
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding ElementName=MyExpander, Path=IsExpanded}" Value="True">
                <Setter TargetName="OuterTextBlock" Property="Opacity" Value="0.5" />                    
            </DataTrigger>

            <DataTrigger Binding="{Binding ElementName=MyExpander, Path=IsExpanded}" Value="True">
                <Setter TargetName="InnerTextBlock" Property="Foreground" Value="Red" />
            </DataTrigger>

            <DataTrigger Binding="{Binding ElementName=MyExpander, Path=IsExpanded}" Value="True">
                <Setter TargetName="MyExpander" Property="Header" Value="Expander open" />
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>

    <!-- Resource data for the Expander -->
    <local:MyExpanderData x:Key="MyExpanderData" HeaderName="Test Expander" isExpanded="True" />
</Window.Resources>

<Grid>
    <!-- Our DataTemplate in ContentControl -->
    <ContentControl Name="MyContentControl" Content="{StaticResource MyExpanderData}" />       
</Grid>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

public class MyExpanderData
{
    private bool expanded = false;
    private string headerName = "";

    public bool isExpanded
    {
        get
        {
            return expanded;
        }

        set
        {
            expanded = value;
        }
    }

    public string HeaderName
    {
        get
        {
            return headerName;
        }

        set
        {
            headerName = value;
        }
    }
}

在课程MyExpanderData中存储的数据,然后在我们的BindingDataTemplate。所有属性都存储在DataTemplate中,我们可以通过此类进行设置。