【发布时间】:2019-01-21 17:41:39
【问题描述】:
所以我只是设置了一个项目并添加了一个看起来像这样的自定义 UserControl。
<Grid>
<ItemsControl ItemsSource="{Binding UserViewModel.Users}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<controls:UserCard/>
<TextBlock Text="{Binding Name}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
如您所见,我尝试绑定 Text 属性,但它没有绑定。
现在可能有很多原因导致它的行为如此,因此我将尝试缩小范围。
我创建了一个 BaseViewModel 来保存我的 ViewModel,它看起来像这样。
public class BaseViewModel : ObservableObject
{
public UserViewModel UserViewModel { get; set; } = new UserViewModel();
}
然后我像这样设置了我的 ViewModel
public class UserViewModel : ObservableObject
{
public ObservableCollection<User> Users { get; set; } = new ObservableCollection<User>();
public UserViewModel()
{
Users.Add(new User{Name = "Riley"});
Users.Add(new User{Name = "Riley1"});
}
}
简单,现在我确实有一个看起来像这样并处理 INPC 的 ObservableObject
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在我的MainView.xaml
我已经像这样设置了 DataContext
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new BaseViewModel();
}
}
UserControl 完全一样
这是我实际添加 UserControl 的地方,以便它显示在 MainWindow 中
<ItemsControl ItemsSource="{Binding UserViewModel.Users}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<controls:UserCard/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
现在的问题是它没有绑定数据,我想显示模型中的 Name 属性,但它没有显示它,我不知道为什么,如果我尝试将它绑定到 TextBlock 属性直接在 MainView 中它工作正常。
我不确定它为什么会这样,我想了解原因。 我需要使用 DependencyProperties 吗?还是只是我创建了 BaseViewModel 的新实例?我哪里做错了?
【问题讨论】:
-
我认为您的用户控件没有正确的 XAML...看起来它是 MainWindow 的 XAML,其中包含您的测试 TextBlock。