Wpf EventTrigger不触发某些元素
本文关键字:元素 EventTrigger Wpf | 更新日期: 2023-09-27 18:08:10
我有这样的东西,ListView
和Button
。ListView
也有两个Buttons
。主要思路是点击ListView
中的Button
来禁用TestButton
。点击TestButton
后不改变,但TestButton2
改变。为什么?
<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");
}
}
Trigger
不会触发,因为TestButton
定义在ListView
的VisualTree
之外。要做到这一点,你可以在后面的代码中定义一个布尔属性,并将其设置为EventTrigger
的TargetObject
,以及TestButton
的IsEnabled
属性的绑定源。
背后的代码(与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"/>