![](/img/trans.png)
[英]WPF ItemsControl element DataTrigger doesn`t fire after data changes
[英]WPF data binding with ItemsControl and DataTrigger
我有一個清單,每個清單都有Name,ImageUrl和IsSelected屬性。 圖像顯示在按鈕內,IsSelected為true的圖像周圍帶有紅色邊框。 懸停在其他人周圍也會顯示紅色邊框。 一切正常。
但是,當我單擊另一個項目時,它會將IsSelected值更改為該項目的true(舊項目的false)。
然后,ViewModel說NotifyOfPropertyChange(()=> Foos);
但是邊界什么也沒有發生。 我嘗試遵循此示例https://stackoverflow.com/a/19319456 ,但無濟於事。 如果可以發現錯誤,則下面是我的xaml代碼。
<ItemsControl ItemsSource="{Binding Foos}" Grid.Column="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Tag="{Binding FooName}" Click="SelectFoo" Cursor="Hand">
<Image Height="100" Width="100" Source="{Binding ImageUrl}"/>
<Button.Template>
<ControlTemplate TargetType="Button">
<Border BorderThickness="1" CornerRadius="3">
<ContentPresenter
Margin="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
RecognizesAccessKey="True"/>
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="#292929"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="Firebrick"/>
</Trigger>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="BorderBrush" Value="Firebrick" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我認為Your類Foo應該實現INotifyPropertyChanged並在IsSelected屬性更改時調用事件ProprtyChanged。 例如:
public class Foo : INotifyPropertyChanged
{
private string _fooName;
private bool _isSelected;
protected void OnNotifyPropertyChanged(string property)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
public event PropertyChangedEventHandler PropertyChanged;
public string FooName { get => _fooName; set { _fooName = value; OnNotifyPropertyChanged(nameof(FooName)); } }
public bool IsSelected { get => _isSelected; set { _isSelected = value; OnNotifyPropertyChanged(nameof(IsSelected)); } }
}
然后是list和Button click方法的示例實現:
public partial class MainWindow : Window
{
public ObservableCollection<Foo> Foos { get; set; }
= new ObservableCollection<Foo>() { new Foo() { FooName = "A1" }, new Foo { FooName = "A2" }, new Foo() { FooName = "A3" } };
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (var foo in Foos)
foo.IsSelected = false;
foreach (var foo in Foos)
if (foo.FooName == (sender as Button)?.Tag as string)
foo.IsSelected = true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.