有一个带有属性的 UserControl - 类 Item 的集合,在 Item 中是 dep 属性名称。有 ViewModel,需要绑定到项目名称的属性。ViewModel 在 UserControl DataContext 中。
代码:
public partial class UserControl1
{
public ObservableCollection<Item> Items { get; set; }
...
public class Item : DependencyObject
{
public string Name
{
get { return (string)GetValue(NameProperty); }
set { SetValue(NameProperty, value); }
}
public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Item), new
PropertyMetadata(null));
}
public class ViewModel
{
public string Name { get; set; }
}
userControl.DataContext = new ViewModel { Name = "Test" };
<wpfApplication6:UserControl1 x:Name="userControl">
<wpfApplication6:UserControl1.Items>
<wpfApplication6:Item Name="{Binding Name, RelativeSource={RelativeSource FindAncestor,
AncestorType=wpfApplication6:UserControl1}}" />
</wpfApplication6:UserControl1.Items>
</wpfApplication6:UserControl1>
没有工作。请帮我。