我有一个WPF应用程序,我正在使用MVVM设计方法。
我有一个ObservableObject,它包含下面的类Transaction的列表;
public Transaction
{
public string Ammount;
public string Direction;
}
我的ViewModel中的ObservableObject位于
之下public ObservableCollection<Transactions> ListOfUserTransactions
{
get { return _localTransactionData; }
set
{
_localTransactionData = value;
RaisePropertyChanged("ListOfUserTransactions");
}
}
我的观点以这种方式结合;
<DataGrid ItemsSource="{Binding ListOfUserTransactions}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Ammount" Binding="{Binding Path=Ammount}" Foreground="Black" IsReadOnly="True" />
<DataGridTextColumn Header="Direction" Binding="{Binding Path=Direction}" Foreground="Black" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
这确实有效,因为生成的行数与我期望的相同,但所有行都是空的,我认为这是我绑定DataGridTextColumn的方式,但我不确定如何做到这一点,希望有上述问题中有足够的细节。
修改
下面是如何创建交易清单
ObservableCollection<Transaction> _localTransactionData = new ObservableCollection<Transaction>();
public TransactionsViewModel(User passedThroughUser)
{
_user = passedThroughUser;
_listOfTransactions = _user.Transactions;
foreach (var item in _listOfTransactions)
{
LocalTransactionsList tran = new LocalTransactionsList();
tran.Ammount = item.Ammount.ToString(); ;
tran.Direction = item.Direction;
_localTransactionData.Add(tran);
}
}
答案 0 :(得分:4)
你的问题在这里:
public Transaction
{
public string Ammount;
public string Direction;
}
应该是:
public Transaction
{
public string Ammount {get;set;}
public string Direction {get;set;}
}
绑定属性必须具有setter和getter。
答案 1 :(得分:2)
您可以通过将Transaction类更改为此来获取您所追求的行为......
public class Transaction : INotifyPropertyChanged
{
private string _amount;
public string Amount
{
[DebuggerStepThrough]
get { return _amount; }
[DebuggerStepThrough]
set
{
if (value != _amount)
{
_amount = value;
OnPropertyChanged("Amount");
}
}
}
private string _direction;
public string Direction
{
[DebuggerStepThrough]
get { return _direction; }
[DebuggerStepThrough]
set
{
if (value != _direction)
{
_direction = value;
OnPropertyChanged("Direction");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null);
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
这将使WPF绑定引擎能够访问您的属性并正确绑定它们。
有关INPC的更多信息http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx