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

C# 如何在XAML中绑定依赖项属性?,c#,wpf,xaml,custom-controls,C#,Wpf,Xaml,Custom Controls,我有一个用户控件,其中我在其代码隐藏中定义了依赖项属性: public static readonly DependencyProperty MyDependencyPropertyProperty = DependencyProperty.Register( "MyDependencyProperty", typeof(MyType), typeof(MyView), new PropertyMetadata(null)); public MyType MyDepe

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

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);
   }
}
现在我想将视图中的dependecy属性绑定到视图模型中的属性,如下所示:

<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">


这段代码给出了我想要的想法,即使用dependency属性来设置绑定。

通常,您需要设置dependency属性,在这里使用
用户控件

<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>