所以我有一个非常简单的UI设计,带有ListView和一个按钮。 我想在点击按钮时填充列表视图。
<Grid>
<Button Click="ButtonBase_OnClick" Content="Button" HorizontalAlignment="Left" Margin="349,259,0,0" VerticalAlignment="Top" Width="75"/>
<ListView Margin="10,10,10,202" Name="lvUsers" ItemsSource="{Binding SomeData.Users}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
我已将ListView的ItemSource属性绑定为SomeData.Users
,这是一个ObservableCollectiuon,它应该在更新,添加,删除或刷新时通知UI。然后在我拥有列的下方,我将DisplayMember绑定到可观察集合的Name
属性。
这是SomeData
类
public class SomeData
{
public static ObservableCollection<User> Users { get; } = new ObservableCollection<User>();
public static void Populate()
{
Users.Add(new User() { Name = "John Doe", Age = 42, Mail = "john@doe-family.com" });
Users.Add(new User() { Name = "Jane Doe", Age = 39, Mail = "jane@doe-family.com" });
Users.Add(new User() { Name = "Sammy Doe", Age = 7, Mail = "sammy.doe@gmail.com" });
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Mail { get; set; }
}
这是MainWindow.cs
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
SomeData.Populate();
}
afaik我不应该在任何地方设置DataContext ..对吗?
答案 0 :(得分:5)
问题是您的Binding语法错误。您正在尝试绑定到静态属性,请尝试以下操作:
[Thu Jun 14 05:03:22.973799 2018] [ssl:trace2] [pid 13154] ssl_engine_rand.c(126): Init: Seeding PRNG with 144 bytes of entropy
[Thu Jun 14 05:03:22.973834 2018] [ssl:info] [pid 13154] AH01887: Init: Initializing (virtual) servers for SSL
[Thu Jun 14 05:03:22.973840 2018] [ssl:info] [pid 13154] AH01876: mod_ssl/2.4.25 compiled against Server: Apache/2.4.25, Library: OpenSSL/1.0.2h
[Thu Jun 14 05:03:22.973858 2018] [http2:debug] [pid 13154] mod_http2.c(103): AH03089: initializing post config dry run
[Thu Jun 14 05:03:22.974292 2018] [core:emerg] [pid 13154] (22)Invalid argument: AH00024: Couldn't set permissions on the rewrite-map mutex; check User and Group directives
AH00016: Configuration Failed
或者如果您使用的是WPF 4.5或更新版本:
"{Binding Source={x:Static YourNameSpace:SomeData.Users}}"
一个提示:像你这样的问题总是试着看看你的输出窗口并寻找"{Binding Path=(YourNameSpace:SomeData.Users)}"
,这些通常是绑定表达式无法解析时发生的绑定异常。在你的情况下,我相信你会发现这个例外。
答案 1 :(得分:2)
您必须为xaml设置DataContext。
将datacontext添加到主窗口
public MainWindow()
{
InitializeComponent();
this.DataContext = new SomeData();
}
并将xaml ItemsSource绑定更改为
ItemsSource="{Binding Users}"