我有一个Foos列表,每个都有Name,ImageUrl和IsSelected属性。图像显示在按钮内,IsSelected为真的图像周围有红色边框。徘徊在其他人周围也显示红色边框。一切正常。
但是当我点击另一个项目时,它会将IsSelected值更改为true(对于旧项目为false)。
ViewModel然后说NotifyOfPropertyChange(()=> Foos);
但边界没有任何反应。我试图按照这个例子https://stackoverflow.com/a/19319456无济于事。如果你能发现错误,下面是我的xaml代码。
CREATE TABLE IF NOT EXISTS myTable
答案 0 :(得分:1)
我认为您的类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;
}
}