如何在 XAML 中绑定依赖项 属性?

How to bind a dependency property in XAML?

我有一个用户控件,我在其中的代码隐藏中定义了一个依赖项 属性:

public static readonly DependencyProperty MyDependencyPropertyProperty = DependencyProperty.Register(
   "MyDependencyProperty", typeof(MyType), typeof(MyView), new PropertyMetadata(null));

public MyType MyDependencyProperty
{
   get
   {
      return (MyType)GetValue(MyDependencyPropertyProperty);
   }
   set
   {
      SetValue(MyDependencyPropertyProperty, value);
   }
}

现在我想在我的视图中将此依赖项 属性 绑定到我的视图模型中的 属性,如下所示:

<UserControl x:Class="Myproject.Views.MyViewView"
             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" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="1000"
             **MyDependencyPropertyProperty {Binding MyPropetyInViewModel}**
             Name="MyView">

这段代码是为了让您了解我想要什么,使用依赖项 属性 来设置绑定。

通常,您会在使用 UserControl.

的地方设置依赖项 属性
<MyViewView MyDependencyPropertyProperty="{Binding MyPropetyInViewModel}" />

如果您真的想在控件本身中这样做,您可以创建一个样式来设置值。

<UserControl x:Class="Myproject.Views.MyViewView"
             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" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
             xmlns:local="clr-namespace:Myproject.Views"
             mc:Ignorable="d" 
             d:DesignHeight="450"
             d:DesignWidth="1000"
             Name="MyView">
   <UserControl.Style>
      <Style>
         <Setter Property="local:MyViewView.MyDependencyPropertyProperty" Value="{Binding MyPropetyInViewModel}"/>
      </Style>
   </UserControl.Style>
   <!-- ...other markup -->
</UserControl>