Wpf EventTrigger没有触发某些元素

时间:2015-08-17 08:31:06

标签: c# wpf

我有类似的内容,ListViewButtonListView也有两个Buttons。主要想法是点击Button中的ListView来禁用TestButton。 点击TestButton后,请勿更改TestButton2。为什么呢?

XAML:

<Grid>
    <ListView ItemsSource="{Binding Items}" Height="200" Width="200">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition></ColumnDefinition>
                        <ColumnDefinition></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Button Content="Test" Grid.Column="0" Height="20" Width="20">
                        <ei:Interaction.Triggers>
                            <ei:EventTrigger EventName="Click">
                                <i:ChangePropertyAction TargetName="TestButton" PropertyName="IsEnabled" Value="False"></i:ChangePropertyAction>
                                <i:ChangePropertyAction TargetName="TestButton2" PropertyName="IsEnabled" Value="False"></i:ChangePropertyAction>
                            </ei:EventTrigger>
                        </ei:Interaction.Triggers>
                    </Button>
                    <Button x:Name="TestButton2" Content="Test2" Grid.Column="1" Height="20" Width="20"></Button>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <Button x:Name="TestButton" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>
</Grid>

xaml.cs:

public class Data
{
    public List<string> Items {get;set;}
    public Data()
    {
        Items= new List<string>();
        Items.Add("Test");
    }
}

1 个答案:

答案 0 :(得分:0)

由于在Trigger TestButton之外定义了ListViewVisualTree无法触发。要使其工作,您可以在代码后面定义一个布尔属性,并将其设置为TargetObject的{​​{1}}以及EventTrigger的{​​{1}}属性的绑定源。

背后的代码(实现了INotifyPropertyChanged ):

IsEnabled

第二个TestButton应该像这样改变:

    bool _btnIsEnable;
    public bool ButtonIsEnable
    {
        get
        {
            return _btnIsEnable;
        }
        set
        {
            _btnIsEnable = value;
            OnPropertyChanged("ButtonIsEnable");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ButtonIsEnable = true;
    }

ChangePropertyAction的绑定应如下所示:

<i:ChangePropertyAction TargetObject="{Binding RelativeSource=
        {RelativeSource AncestorType=Window}, Path=.}
        "PropertyName="ButtonIsEnable" Value="False"/>