我試圖填寫ListBox
ObservableCollection
。但是,當我添加新項目什麼都沒有顯示,只有空項目添加。ObservableCollection和DisplayMemberBinding
有我的代碼片段: 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>
Window類
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類
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);
}
}
當我嘗試添加新項目,新項目將被添加,但不顯示任何內容。什麼原因可以在這裏?
你似乎很困惑......你爲什麼要在你的視圖模型中實現你的數據類型屬性?你不應該在'OnPropertyChanged'處使用'ValueX'和'ValueY' ...你應該在你的'Point'數據類型中有*那個*代碼。您應該在Visual Studio的「輸出」窗口中看到綁定錯誤...它說了什麼? – Sheridan
不,沒有任何exeptions – Bashnia007
在Visual Studio中,轉到工具>選項>調試>輸出窗口> WPF跟蹤設置,並將'數據綁定'選項設置爲'警告'或'錯誤'。您可以從MSDN的[How to:Display WPF Trace Information](http://msdn.microsoft.com/zh-cn/library/dd409960.aspx)頁面找到更多信息。 – Sheridan