如何以编程方式添加DataTrigger

时间:2015-11-24 21:30:57

标签: c# wpf .net-4.0 datatrigger

我需要根据用户与搜索功能的交互动态添加DataTrigger,因此无法在XAML中完成。但是,我正在尝试做的基本目标可以从下面的XAML代码中看到。它需要根据ToggleButton的IsChecked状态更改按钮的可见性。

XAML:

<ToggleButton Name="myToggleButton" />

<Button Name="myButton">
    <Style TargetType="Button">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=myToggleButton, Path=IsChecked}"
                         Value="True">
                <Setter Property="Visibility" Value="Collapsed" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=myToggleButton, Path=IsChecked}"
                         Value="False">
                <Setter Property="Visibility" Value="Collapsed" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Button>

这就是我在C#中尝试生成上述XAML的相同功能。

C#:

ToggleButton myToggleButton = new ToggleButton();
Button myButton = new Button();
Style style = new Style( typeof( Button ) );
DataTrigger tbChecked = new DataTrigger() 
{ 
    Binding = new Binding( "IsChecked" ) { Source = myToggleButton },
    Value = true
},
            tbNotChecked = new DataTrigger() 
{ 
    Binding = new Binding( "IsChecked" ) { Source = myToggleButton },
    Value = false
};
tbChecked.Setters.Add( new Setter( Button.VisibilityProperty, Visibility.Visible ) );
tbNotChecked .Setters.Add( new Setter( Button.VisibilityProperty, Visibility.Collapsed ) );
style.Triggers.Add( tbChecked );
style.Triggers.Add( tbNotChecked );
myButton.Style = style;

对于我的生活,我一直无法弄清楚为什么它不会起作用。我错过了什么?

1 个答案:

答案 0 :(得分:0)

也许,你可以试试这个:

<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
    <StackPanel.Resources>
        <BooleanToVisibilityConverter x:Key="b2v"/>
    </StackPanel.Resources>

    <CheckBox x:Name="switchCheckBox" Content="Show/Hide" VerticalAlignment="Center"/>
    <TextBlock Text=" "/>
    <Button Content="Test Button" Visibility="{Binding ElementName=switchCheckBox, Path=IsChecked, Converter={StaticResource b2v}}" Padding="25,5"/>

</StackPanel>