我正在努力弄清楚WPF和C#的數據綁定和項目源,並且我錯過了一些東西,當涉及到進行適當的綁定連接時。其結果是一個運行時錯誤:當我按下按鈕時試圖添加一些東西到ListView中
Cannot find source for binding with reference 'ElementName=SettingsWindow'. BindingExpression:Path=teams; DataItem=null; target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
代碼本身是非常簡單的(我認爲):
SettingsWindow.xaml:
<Window x:Class="Bridge.SettingsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Settings" Height="480" Width="600">
...
<Button Grid.Column="0" Grid.Row="0" Content="Add Team" Click="ClickAddTeam"/>
<ListView ItemsSource="{Binding}" Grid.Column="0" Grid.Row="1">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Foreground" Value="{Binding team.color}" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
...
</Window>
SettingsWindow.xaml.cs:
public partial class SettingsWindow : Window
{
public TeamList teams { get; set; }
public SettingsWindow()
{
teams = TeamManager.Instance().teamList; // persists in a different class
this.DataContext = this.teams;
InitializeComponent();
}
private void ClickAddTeam(object sender, RoutedEventArgs e)
{
TeamManager manager = TeamManager.Instance();
Team toAdd = manager.GetSampleTeam(teams.Count);
Console.WriteLine(toAdd.ToString());
teams.Add(toAdd);
if(teams.Count == manager.sampleTeams.Count)
(sender as Button).IsEnabled = false;
}
}
Team.cs:
namespace DataTypes
{
public class Team
{
public string name;
public Brush color;
public Team(string name, Brush color)
{
this.name = name;
this.color = color;
}
}
}
現在的工作:
在ClickAddTeam中的WriteLine正在打印正確的數據,所以我知道它的檢索團隊對象正確和該MyTeamList teams
對象獲得的東西添加進去。該按鈕在適當的點擊次數後也被禁用。但是,ListBox始終保持空白。
下一步: 我試圖讓ListBox中的字符串是隊。名稱,而不是「DataTypes.Team」,併爲文字的前景是球隊的顏色。我如何獲取綁定元素的特定屬性?
任何幫助將不勝感激!
那你有沒有設定一個數據上下文? this.DataContext = this; SettingsWindow是否已定義? – Paparazzi
我認爲'ElementName = SettingsWindow'會以相同的名稱指向代碼隱藏類;是不是這樣?無論如何,我有一些工作,但它顯示「DataTypes.Team」,而不是任何類型的字符串。我該如何使用對象填充列表框,但指定要顯示的字符串? – Benjin