WPF绑定问题
例如,我有:
MainWindows.cs
public partial class MainWindow : Window
{
public List<Player> List;
public MainWindow()
{
InitializeComponent();
List = new List<Player>()
{
new Player() {Id = 1, Name = "Tom"},
new Player() {Id = 2, Name = "Bob"},
new Player() {Id = 3, Name = "Any"},
};
comboBox1.DataContext = List;
}
public class Player
{
public string Name { get; set; }
public int Id { get; set; }
}
}
XAML:
我如何(需要)将 List 设置为 DataContext XAML? (并从代码隐藏中删除“comboBox1.DataContext = List”)
For example, I have:
MainWindows.cs
public partial class MainWindow : Window
{
public List<Player> List;
public MainWindow()
{
InitializeComponent();
List = new List<Player>()
{
new Player() {Id = 1, Name = "Tom"},
new Player() {Id = 2, Name = "Bob"},
new Player() {Id = 3, Name = "Any"},
};
comboBox1.DataContext = List;
}
public class Player
{
public string Name { get; set; }
public int Id { get; set; }
}
}
XAML: <ComboBox ItemsSource="{Binding}" DisplayMemberPath="Name"/>
How I can (need to) set List as a DataContext from the XAML? (and delete "comboBox1.DataContext = List" from the code-behind)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非您使用 MVVM,否则您不需要这样做,但在任何情况下,使用都可以将 List 创建为窗口的属性,如下所示
,然后在 XAML 中您可以使用relativeSource 进行绑定到窗口:
或者,您可以为窗口命名:
然后在绑定中使用 ElementName,如下所示:
unless you're using MVVM u don't need to do that, but in any case, use can create the List as a property of the window like so
and then in XAML u can use RelativeSource to bind to the window:
alternatively, u can give a name to your window:
and then use ElementName in the binding, like so:
快速修复方法是直接在代码隐藏中设置 ComboBox 的 ItemsSource(而不是 DataContext),但为了能够使用正确的绑定,您需要一个 ViewModel 或至少一个 XAML DataContext。
此外,您还应该为列表选择一些比 List 更独特的名称,例如 Players - 使用列表中对象类型的复数形式是一个很好的做法。
Quick fix is setting your ComboBox's ItemsSource directly in code-behind (instead of DataContext), but in order to be able to use proper bindings you'll need a ViewModel or at least a XAML DataContext.
Also you should pick some more unique name than List for your List, like for example Players – it's good practice to use the plural form of the type of Objects in the List.