我的绑定不起作用。我搜索了错误,但我不明白如何在我的情况下修复它。
System.Windows.Data 错误:1:无法创建默认转换器以在类型“MyApplication.MyUserControl”和“MyApplication.Person”之间执行“单向”转换。考虑使用 Binding 的 Converter 属性。绑定表达式:路径=;DataItem='MyUserControl' (Name=''); 目标元素是'MyUserControl'(名称='');目标属性是“PersonInfo”(类型“Person”)
System.Windows.Data 错误:5:BindingExpression 生成的值对目标属性无效。;Value='MyApplication.MyUserControl' BindingExpression:Path=; DataItem='MyUserControl' (Name=''); 目标元素是'MyUserControl'(名称='');目标属性是“PersonInfo”(类型“Person”)
基本上它是一个绑定到 Person 类的 ObservableCollection 的 ListView。
主窗口.xaml.cs
public partial class MainWindow : Window
{
public ObservableCollection<Person> PersonCollection { set; get; }
public MainWindow()
{
PersonCollection = new ObservableCollection<Person>();
InitializeComponent();
PersonCollection.Add(new Person() { Name = "Bob", Age = 20 });
}
}
主窗口.xaml
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" xmlns:self="clr-namespace:MyApplication" x:Class="MyApplication.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ListView ItemsSource="{Binding PersonCollection}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<self:MyUserControl PersonInfo="{Binding}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window>
MyUserControl.xaml.cs
public partial class MyUserControl : UserControl
{
public static readonly DependencyProperty PersonProperty = DependencyProperty.Register("PersonInfo", typeof(Person), typeof(MyUserControl));
public Person PersonInfo
{
get { return (Person)GetValue(PersonProperty); }
set { SetValue(PersonProperty, value); }
}
public MyUserControl()
{
InitializeComponent();
}
}
MyUserControl.xaml
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}" x:Class="MyApplication.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<TextBlock Text="{Binding PersonInfo.Name}" />
</UserControl>
个人.cs
public class Person : INotifyPropertyChanged
{
public int Age { set; get; }
public string Name { set; get; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}