簡體   English   中英

如何在 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);
   }
}

現在我想在我的視圖中將此依賴屬性綁定到我視圖中的屬性 model,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM