我正试图通过ListBox
填充ObservableCollection
。但是当我添加新项目没有显示时,只添加空项目。
我的代码有片段:
XAML
<ListView ItemsSource="{Binding Points}" SelectedItem="{Binding Point}">
<ListView.View>
<GridView AllowsColumnReorder="False">
<GridViewColumn Header ="X" Width="100" DisplayMemberBinding = "{Binding Path=ValueX, Mode=TwoWay}" />
<GridViewColumn Header ="Y" Width="100" DisplayMemberBinding = "{Binding Path=ValueY, Mode=TwoWay}"/>
</GridView>
</ListView.View>
</ListView>
窗口类
var value = new Value();
var viewModel = new ViewModel(value);
DataContext = viewModel;
InitializeComponent();
价值等级
private const Point POINT = null;
private readonly ObservableCollection<Point> _points = new ObservableCollection<Point>();
public Value() {
Point = POINT;
Points = _points;
}
public Point Point { get; set; }
public ObservableCollection<Point> Points { get; private set; }
public double ValueX { get; set; }
public int ValueY { get; set; }
ViewModel类
private readonly Value _value;
public ViewModel(Value value) {
_value = value;
}
public Point Point {
get { return _value.Point; }
set {
_value.Point = value;
OnPropertyChanged("Point");
}
}
public ObservableCollection<Point> Points {
get { return _value.Points; }
}
private RelayCommand _addCommand;
public ICommand AddCommand {
get {
if (_addCommand == null) {
_addCommand = new RelayCommand(Add);
}
return _addCommand;
}
}
private void Add(object obj) {
Points.Add(new Point(ValueX, ValueY));
ValueX = 0;
ValueY = 0;
}
public double ValueX {
get {
return _value.ValueX;
}
set {
if(Math.Abs(_value.ValueX - value) < Mathematics.EPSILON) return;
_value.ValueX = value;
OnPropertyChanged("ValueX");
}
}
public int ValueY {
get { return _value.ValueY; }
set {
if(_value.ValueX == value) return;
_value.ValueY = value;
OnPropertyChanged("ValueY");
}
}
和Point class
public class Point {
public readonly double ValueX;
public readonly double ValueY;
public Point(double valueX, double valueY) {
ValueX = valueX;
ValueY = valueY;
}
public override string ToString() {
return (ValueX + " " + ValueY);
}
}
当我尝试添加新项目时,会添加新项目但不会显示任何内容。可以在这里找到什么理由?
答案 0 :(得分:1)
由于您将ItemsSource
绑定到ObservableCollection<Point>
,这意味着每个项目都属于Point
类型,其中ValueX
和ValueY
被声明为字段,而不是有效的绑定源。将它们更改为属性:
public double ValueX { get; private set; }
public double ValueY { get; private set; }
除了你使用Mode=TwoWay
作为只读的东西。这应该更改为OneWay
。如果您要保留TwoWay
绑定,请从设置器中删除private
,但您还需要将GridViewColumn.CellTemplate
更改为某些TextBox
,而不是使用DisplayMemberBinding
}仅供显示。