簡體   English   中英

綁定附屬物

[英]Binding to attached property

我正在嘗試將Button的ContentTemplate綁定到附加屬性。 我讀了所有問題的答案,類似於“綁定到附屬物”,但我沒有解決問題的運氣。

請注意,此處提供的示例是我的問題的一個愚蠢的版本,以避免混亂業務代碼的問題。

所以,我確實有附加屬性的靜態類:

using System.Windows;

namespace AttachedPropertyTest
{
  public static class Extender
  {
    public static readonly DependencyProperty AttachedTextProperty = 
      DependencyProperty.RegisterAttached(
        "AttachedText",
        typeof(string),
        typeof(DependencyObject),
        new PropertyMetadata(string.Empty));

    public static void SetAttachedText(DependencyObject obj, string value)
    {
      obj.SetValue(AttachedTextProperty, value);
    }

    public static string GetAttachedText(DependencyObject obj)
    {
      return (string)obj.GetValue(AttachedTextProperty);
    }

  }
}

和一個窗口:

<Window x:Class="AttachedPropertyTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:AttachedPropertyTest"
        Title="MainWindow" Height="350" Width="525">
  <Grid>
    <Button local:Extender.AttachedText="Attached">
      <TextBlock 
        Text="{Binding 
          RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button},
          Path=(local:Extender.AttachedText)}"/>
    </Button>
  </Grid>
</Window>

這就是它。 我希望在按鈕中間看到“附加”。 相反它崩潰: 屬性路徑無效。 'Extender'沒有名為'AttachedText'的公共屬性。

我對SetAttachedText和GetAttachedText設置斷點,SetAttachedText 執行,因此將其連接到按鈕的作品。 GetAttachedText永遠不會被執行,所以它在解析時找不到屬性。

我的問題實際上更復雜(我試圖從App.xaml中的Style內部進行綁定)但是讓我們從簡單的開始。

我錯過了什么? 謝謝,

您附屬的財產登記是錯誤的。 ownerTypeExtender ,而不是DependencyObject

public static readonly DependencyProperty AttachedTextProperty = 
    DependencyProperty.RegisterAttached(
        "AttachedText",
        typeof(string),
        typeof(Extender), // here
        new PropertyMetadata(string.Empty));

有關RegisterAttached的信息,請參閱MSDN文檔:

ownerType - 正在注冊依賴項屬性的所有者類型

暫無
暫無

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

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