你绑定到索引器吗?你能告诉我们你的 DataList 属性是什么样的吗?
不久前我对索引属性做了同样的事情。
public SomeObjectWithIndexer DataList
{get; set;}
public class SomeObjectWithIndexer
{
public string this
{
get { ... }
set { ... }//<-- you need this one for TwoWay
}
}
编辑:您无法编辑属性的原因是您尝试编辑“双字段”。一种解决方法是使用 INotifyPropertyChanged 将你的 double 包装到一个类中。
public class DataListItem
{
public double MyValue { get; set;}//with OnPropertyChanged() and stuff
}
那么你可以使用
ObservableCollection<DataListItem>
您可以编辑您的值。索引是否总是相同的问题仍然存在:)
Binding binding = new Binding(string.Format("DataList[{0}].MyValue", n++));
EDIT2:工作示例:只是为了显示双向工作
public class DataItem
{
public string Name { get; set; }
public ObservableCollection<DataListItem> DataList { get; set; }
public DataItem()
{
this.DataList = new ObservableCollection<DataListItem>();
}
}
双包装:
public class DataListItem
{
private double myValue;
public double MyValue
{
get { return myValue; }
set { myValue = value; }//<-- set breakpoint here to see that edit is working
}
}
带有数据网格的用户控件
<UserControl x:Class="WpfStackoverflow.IndexCollectionDataGrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<DataGrid ItemsSource="{Binding MyList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
<DataGridTextColumn Header="Index1" Binding="{Binding Path=DataList[0].MyValue, Mode=TwoWay}" />
<DataGridTextColumn Header="Index2" Binding="{Binding Path=DataList[1].MyValue, Mode=TwoWay}" />
</DataGrid.Columns>
</DataGrid>
</UserControl>
。CS
public partial class IndexCollectionDataGrid : UserControl
{
public IndexCollectionDataGrid()
{
InitializeComponent();
this.MyList = new ObservableCollection<DataItem>();
var m1 = new DataItem() {Name = "test1"};
m1.DataList.Add(new DataListItem() { MyValue = 10 });
m1.DataList.Add(new DataListItem() { MyValue = 20 });
var m2 = new DataItem() { Name = "test2" };
m2.DataList.Add(new DataListItem() { MyValue = 100 });
m2.DataList.Add(new DataListItem() { MyValue = 200 });
this.MyList.Add(m1);
this.MyList.Add(m2);
this.DataContext = this;
}
public ObservableCollection<DataItem> MyList { get; set; }
}
我希望你通过这个例子找到正确的方向。