Wpf EventTrigger不触发某些元素

本文关键字:元素 EventTrigger Wpf | 更新日期: 2023-09-27 18:08:10

我有这样的东西,ListViewButtonListView也有两个Buttons。主要思路是点击ListView中的Button来禁用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");
    }
}

Wpf EventTrigger不触发某些元素

Trigger不会触发,因为TestButton定义在ListViewVisualTree之外。要做到这一点,你可以在后面的代码中定义一个布尔属性,并将其设置为EventTriggerTargetObject,以及TestButtonIsEnabled属性的绑定源。

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

    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"/>

TestButton的绑定应该是这样的:

<Button x:Name="TestButton" Content="Button" IsEnabled="{Binding ButtonIsEnable}" 
        HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>