我肯定不是新的C#和.NET,但因爲我沒有使用XAML打了相當長的時間,我現在面臨一個非常簡單的問題...新手問題與DataContext的和綁定
我創建了一個測試模型(ResultsModel
)像這樣:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Test_Project_
{
public class ResultsModel : INotifyPropertyChanged
{
private string _Monthly;
public string Monthly
{
get { return _Monthly; }
set { _Monthly = value; NotifyPropertyChanged("Monthly"); }
}
private string _TotalAmount;
public string TotalAmount
{
get { return _TotalAmount; }
set { _TotalAmount = value; NotifyPropertyChanged("TotalAmount"); }
}
private string _TotalInterest;
public string TotalInterest
{
get { return _TotalInterest; }
set { _TotalInterest = value; NotifyPropertyChanged("TotalInterest"); }
}
List<Dictionary<string, double>> _Items;
public List<Dictionary<string, double>> Items
{
get { return _Items; }
set { _Items = value; NotifyPropertyChanged("Items"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}
在我MainPage
類:
public ResultsModel Results;
public MainPage()
{
InitializeComponent();
Results = new ResultsModel();
DataContext = Results;
}
現在,這裏的漁獲:
當我試圖綁定例如一個TextBlock
的Text
屬性我的模型的一些簡單的字符串值(例如Text={Binding Monthly}
),它的工作原理。
現在請注意,我也有一個網格,有四列。
我想將我的Items
屬性(ResultsModel
)中的所有項目都拿回來,並通過鍵在網格中顯示它們。
E.g.
顯示列表項的「A」鍵,在「A」欄(假設網格的第一列)等
我如何能做到這一點(在XAML和/或C#代碼)?
UPDATE:
(根據建議,我嘗試以下,但仍無法正常工作)
內Grid
XAML:
<ItemsControl ItemsSource="{Binding Items, Mode=TwoWay}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Grid.Column="0" Text="{Binding Path=num}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
但我收到以下錯誤:
System.Windows.Data Error: BindingExpression path error: 'num' property not found on 'System.Collections.Generic.Dictionary
2[System.String,System.String]' 'System.Collections.Generic.Dictionary
2[System.String,System.String]' (HashCode=57616766). BindingExpression: Path='num' DataItem='System.Collections.Generic.Dictionary`2[System.String,System.String]' (HashCode=57616766); target element is 'System.Windows.Controls.TextBlock' (Name=''); target property is 'Text' (type 'System.String')..
此外,請不要將Items
轉換爲字符串字符串鍵值對列表。
任何想法?
而不是使用網格,你應該採取某種itemscontrol來顯示你的收藏。 – blindmeis
在WPF中,可以在綁定中使用索引器:'Text = {Binding Path = Items [A]}'。我不記得是否可以在Windows Phone上使用。在最糟糕的情況下,您可以使用轉換器爲您完成工作。 –
索引器將工作,但它不動態 - 當它不動態時,您可以在您的模型中爲每個「硬」索引創建屬性獲取器 – blindmeis