【发布时间】:2020-01-10 16:27:33
【问题描述】:
所以我有一个简单的 wpf 应用程序,我将其用作练习。 它基于动物园的想法,我有 3 种动物类型(大象、长颈鹿、猴子)。
每个都有一个健康属性和一个 IsDead 属性。
这两个属性都是 Animal 类的一部分,我的 Elephant 类、Giraffe 类和 Monkey 类都继承自该类。
我希望能够以更改健康字段为例,并使用这些值更新列表视图。
到目前为止,所创建的项目都没有在屏幕上更新。我知道这会很简单,但任何帮助都会很棒。提前致谢。
查看:
<ListView Margin="5"
Name="lstMonkey"
Width="150"
ItemsSource="{Binding MonkeyList}">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="Index" />
<!-- DisplayMemberBinding="{Binding Path=}" /-->
<GridViewColumn Header="Health"
DisplayMemberBinding="{Binding Path=Monkey.Health}" />
<GridViewColumn Header="Is Dead"
DisplayMemberBinding="{Binding Path=Monkey.IsDead}" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
型号:
public class Monkey : Animal
{
const int m_MinimumHealth = 30;
public void CheckIsDead()
{
if (Health < m_MinimumHealth)
{
IsDead = true;
}
else IsDead = false;
}
}
public class Animal
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
public float Health
{
get { return m_Health; }
set
{
m_Health = value;
OnPropertyChanged("Health");
}
}
public bool IsDead
{
get { return m_IsDead; }
set
{
m_IsDead = value;
OnPropertyChanged("IsDead");
}
}
public int Index
{
get { return m_Index; }
set
{
m_Index = value;
OnPropertyChanged("Index");
}
}
}
public class MainWindowViewModel
{
public MainWindowViewModel()
{
MonkeyList = new ObservableCollection<Monkey>();
for (int i = 0; i < 5; i++)
{
MonkeyList.Add(new Monkey {Index = i, Health = 100, IsDead = false});
}
OnPropertyChanged("MonkeyList");
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
}
}
}
【问题讨论】:
-
请删除您的代码 cmets。我已将它们添加到您的问题中。
-
确保有一个 MainWindowViewModel 实例分配给 MainWindow 的 DataContext。除此之外,
Path=Monkey.Health和Path=Monkey.IsDead应该是Path=Health和Path=IsDead。 -
感谢您组织得更好。 BionicCode,以供将来参考,这样做的最佳方法是什么,以便在将其放入问题时可读?
标签: c# wpf listview mvvm binding