バインディングが機能しません。エラーを検索しましたが、私の場合の修正方法がわかりません。
System.Windows.Dataエラー:1:タイプ「MyApplication.MyUserControl」と「MyApplication.Person」の間で「一方向」変換を実行するデフォルトのコンバーターを作成できません。BindingのConverterプロパティの使用を検討してください。BindingExpression:Path =; DataItem ='MyUserControl'(Name =''); ターゲット要素は'MyUserControl'(Name ='');です。ターゲットプロパティは「PersonInfo」(タイプ「Person」)です
System.Windows.Dataエラー:5:BindingExpressionによって生成された値はターゲットプロパティに対して無効です。; Value ='MyApplication.MyUserControl' BindingExpression:Path =; DataItem ='MyUserControl'(Name =''); ターゲット要素は'MyUserControl'(Name ='');です。ターゲットプロパティは「PersonInfo」(タイプ「Person」)です
基本的には、PersonクラスのObservableCollectionにバインドされているListViewです。
MainWindow.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 });
}
}
MainWindow.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>
Person.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));
}
}