Skip to main content
 首页 » 编程设计

c#之当 UserControl 具有 DataContext 时,UserControl 的 DependencyProperty 为 null

2024年02月06日11pengyingh

我已将 DependencyProperty 添加到我的 View ,绑定(bind)到 DependencyProperty 有效,但前提是我还没有设置 DataContext。

GenericView.xaml

<UserControl x:Class="GenericProject.View.GenericView" 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <StackPanel> 
        <Button Command="{Binding VMFactory.CreateViewModelCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /> 
        <TextBox IsEnabled="False" Text="{Binding SomeProperty, Mode=OneWay}" /> 
    </StackPanel> 
</UserControl> 

GenericView.xaml.cs

public partial class GenericView : UserControl 
{ 
    // The DependencyProperty for VMFactory. 
    public static readonly DependencyProperty VMFactoryProperty = DependencyProperty.Register("VMFactory", typeof(VMFactoryViewModel<GenericViewModel>), typeof(GenericView)); 
 
    public VMFactoryViewModel<GenericViewModel> VMFactory 
    { 
        get { return (VMFactoryViewModel<GenericViewModel>)GetValue(VMFactoryProperty); } 
        set { SetValue(VMFactoryProperty, value); } 
    } 
 
    public GenericView() 
    { 
        InitializeComponent(); 
    } 
} 

我在这里创建了两个 View 来说明手头的问题。第一个 View 中的 VMFactory 绑定(bind)将失败,因为我设置了 DataContext。第二个 View 会成功,请问是什么原因造成的?

MainPage.xaml

<vw:GenericView DataContext="{Binding Generic}" VMFactory="{Binding GenericFactory}" /> 
<vw:GenericView VMFactory="{Binding GenericFactory}" /> 

请您参考如下方法:

这是一个相当常见的绑定(bind)“问题”...

为了访问VMFactory , 你需要绑定(bind)你的 UserControl对自己使用...

DataContext="{Binding RelativeSource={RelativeSource Self}}" 

你不会再绑定(bind) DataContext在 GenericView 上项目到其他任何地方。

但是,如果您打算将其他值绑定(bind)到 VMFactory UserControl 外部(即 <vw:GenericView VMFactory={Binding ...}"/> ),你应该使用 RelativeSource使用模式 FindAncestor对于类型 UserControl .

<!-- Shortened to show pertinent Binding --> 
<ctrl:CommandTextBox Command="{Binding VMFactory.CreateViewModelCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}"/>