0

我正在努力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; }

视图模型类

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");
        }
    }

和点类

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);
    }
}

当我尝试添加新项目时,会添加新项目但没有显示任何内容。什么原因可以在这里?

4

1 回答 1

1

由于您绑定ItemsSourceObservableCollection<Point>它意味着每个项目都是Point具有ValueXValueY声明为无效绑定源的字段的类型。将它们更改为属性:

public double ValueX { get; private set; }
public double ValueY { get; private set; }

除了你使用Mode=TwoWay只读的东西。这应该更改为OneWay. 如果您想离开TwoWay绑定private,则从设置器中删除,但您还需要更改GridViewColumn.CellTemplate为 someTextBox而不是DisplayMemberBinding仅用于显示。

于 2013-08-21T08:35:17.547 回答