带有DataContext的UserControl的DependencyProperty

3

我有一个ListBox,使用UserControl作为DataTemplate。我的UserControl有一个ViewModel。在我的UserControl中有一个DependencyProperty,这样我可以将来自ListBox的项目绑定到我的UserControl。

除非我不给我的UserControl设置任何DataContext,否则它不起作用。

我如何在我的UC中同时使用DP和自定义DataContext?

我的ListBox:

<ListBox ItemsSource="{Binding Path=ListItems, Mode=TwoWay}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <local:MyCustomUC MyObject="{Binding Path=.}"/>
             </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我的用户控件XAML:

<UserControl x:Class="UserControlDataTemplate.MyCustomUC"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="Auto" Width="Auto">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=FromViewModel}" />
        <Button Content="{Binding ElementName=MyObject, Path=FromParent}" />
    </StackPanel>
</UserControl>

我的用户控件CS:

       public MyClass MyObject
        {
            get { return (MyClass)GetValue(MyObjectProperty); }
            set
            {
                SetValue(MyObjectProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyObjectProperty =
        DependencyProperty.Register("MyObject", typeof(MyClass), typeof(MyCustomUC), new PropertyMetadata(null));

        public MyCustomUC()
        {
           InitializeComponent();

           this.DataContext = new MyCustomUCViewModel();
        }

My ViewModel:

    public class MyCustomUCViewModel : DependencyObject, INotifyPropertyChanged
    {
        public String FromViewModel { get; set; }

        public MyCustomUCViewModel()
        {
            this.FromViewModel = Guid.NewGuid().ToString();
        }
        ...
     }

从ListBox中的ItemSource获取的Item类:

public class MyClass : INotifyPropertyChanged
{
    public String FromParent { get; set; }
    ...
}

我做错了什么?
1个回答

1

这里你是在 MyCustomUC() 中设置 DataContext
相反,你可以像这样设置 DataContext

<vm:YourViewModel x:Name="VModel" IfPropertToSet="{BindingFromExistingDC}"/>  

<ListBox ItemsSource="{Binding Path=ListItems, Mode=TwoWay}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <local:MyCustomUC MyObject="{Binding Path=.}" DataContext="{Binding ElementName=VModel}" />
             </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

你需要包含命名空间

xmlns:vm="clr-namespace:YourViewModelPath"

1
但问题是为什么绑定引擎使用在UserControl中设置的DataContext,而不是包含控件(在此情况下由ListBox生成)的DataContext?为什么在XAML中设置DataContext与在代码中设置DataContext的效果不同呢? - serine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接