有一个带有属性的UserControl - 类Item的集合,在Item中是dep属性Name。有ViewModel,需要绑定到Name of Item的属性。 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>
没有工作。求你帮帮我。
答案 0 :(得分:0)
<wpfApplication6:UserControl1 x:Name="userControl">
<wpfApplication6:UserControl1.Items>
<wpfApplication6:Item Name="{Binding Path=DataContext.Name, RelativeSource={RelativeSource FindAncestor,
AncestorType=wpfApplication6:UserControl1}}" />
</wpfApplication6:UserControl1.Items>
</wpfApplication6:UserControl1>