我正在努力找出使用WPF和C#的数据绑定和项目源,并且在制作正确的绑定连接时我遗漏了一些东西。结果是运行时错误:
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正在打印正确的数据,因此我知道它正确地检索了Team对象和 MyTeamList teams
对象正在添加的东西它。经过适当的点击次数后,该按钮也被禁用。但是,ListBox在整个时间内都保持为空。
下一步: 我试图让ListBox中的字符串成为 team .name而不是&#34; DataTypes.Team&#34;,并且文本的前景是团队的颜色。如何获取绑定元素的特定属性?
非常感谢任何帮助!
答案 0 :(得分:1)
绑定仅适用于公共属性。尝试将teams
声明为属性而不是字段/成员:
public MyTeamList teams { get; set; }
// OP注意:下面这部分不会编译,给我一个member names cannot be the same as their enclosing type
错误。
因为您要ElementName
绑定,所以您需要正确命名Window
:
<Window x:Class="Bridge.SettingsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="SettingsWindow"
Title="Settings" Height="480" Width="600">
[OP Note]
只需将该行更改为ItemsSource="{Binding}"
即可用于显示内容,但每个项目都显示为&#34; DataType.Team&#34;而不是一个正确的字符串。这是下一个要弄明白的事情。
[/ OP Note]
答案 1 :(得分:0)
每个问题应该是一个问题
您需要设置DataContext
this.DataContext = this;
ItemsSource =“{Binding Path = TeamList}”DisplayMemberPath = Name
名称必须是公共财产(get)