簡體   English   中英

綁定到自定義XAML控件屬性將不起作用

[英]Binding to a custom XAML control property won't work

我正在嘗試使用C#和XAML創建Windows 10 UWP應用程序。 在這一點上,我對項目模板中的數據綁定非常感興趣。

所以基本上,我有一個ViewModel,它綁定到XAML控件。

我想將數據模型綁定到自定義控件的屬性。 問題是有些事情行之有效,有些卻行不通,我真的不明白為什么。

因此,此綁定有效:

  <GridView   ItemsSource="{Binding MediaElementId}" >
       <GridView.ItemTemplate>
           <DataTemplate>
               <TextBlock Text="{Binding}" />
           </DataTemplate>
        </GridView.ItemTemplate>
   </GridView>

但是,當我將其他東西插入TextBlock時,它將無法工作。

例如,這些綁定將不起作用

<TextBlock  Text="{Binding  Path=.}"/>
 <controls:CustomControl Test="{Binding Path=., UpdateSourceTrigger=PropertyChanged}"  />
 <controls:CustomControl Test="{Binding Path=., RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"/>
 <controls:CustomControl Test="{Binding}"/>

因此,我基本上找到了文檔,即{Binding}與{Binding Path =。}等效,但是在此示例中,它似乎並非如此。

您可以在一個我發現問題的項目中自己嘗試: https : //bitbucket.org/MrGreeny/pivottestapp/src/4edee74acfac6dbb4f9f042acaf389cc6fd90a31?at=master

編輯:該屬性是一個非常簡單的屬性:

    private string test;

    public string Test
    {
        get { return null; }
        set
        {
            Debug.WriteLine(value);
           //What i think should be here is for example textblock.Text = value
        }
    }

因此,基本上我要做的就是使用DependencyProperty而不是常規屬性。 這是有效的解決方案:

首先是DataTemplate內部的控件:

<GridView ItemsSource="{Binding MediaElementId}" >
   <GridView.ItemTemplate>
      <DataTemplate>
         <local:CustomControl TextBlockContent="{Binding}" />
      </DataTemplate>
   </GridView.ItemTemplate>
 </GridView>

然后在自定義控件xaml.cs文件中:

首先是包裝程序公開DependencyProperty

public string TextBlockContentProperty
{
    get { return (string)GetValue(TextBlockContentPropertyProperty); }
    set { SetValue(TextBlockContentPropertyProperty, value); }
}

然后是DependencyProperty本身。

     public static readonly DependencyProperty TextBlockContentPropertyProperty =
        DependencyProperty.Register(
           "TextBlockContentProperty", 
           typeof(string), 
           typeof(CustomControl), 
           new PropertyMetadata(0, new PropertyChangedCallback(OnTextChanged)) );

請注意,最后一個參數包含與OnTextChanged函數的連接,在這里我們可以訪問對象實例。 以上所有都是static ,我們不能使用它們來更改對象的實例。

這是我實現實例特定邏輯的方式。 TextBlockContent是常規屬性,它公開TextBlockText屬性,即自定義控件的內容。

    private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        CustomControl cc = d as CustomControl;
        string content = (string)e.NewValue;
        cc.TextBlockContent = content;
    }

感謝所有回答我最初問題的人。

暫無
暫無

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

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