2013-01-08 46 views
0

首先讓我說我對WPF來說比較陌生,所以請原諒我的愚蠢錯誤,但是我現在一直在爲此付出沉重的代價。在WPF上綁定錯誤(對DataContext進行綁定)

我有一個簡單sollution有三類:

public class MyCustomItem 

public class MyCustomLayout : ThirdPartyLayout<MyCustomItem> 

public class MyViewController : INotifyPropertyChanged 

MyCustomItem是一個簡單的類的一些屬性(「名稱」是其中之一)。 ThirdPartyLayoutTool是從System.Windows.Controls.Panel繼承的SDK中的通用組件。 MyViewController是我用作數據內容的視圖控制器。

然後我創造了這個簡單的XAML作爲項目主窗口:

<Window x:Class="DependencyViewer.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:sdk="clr-namespace:Sdk;assembly=Sdk" 
    xmlns:local="clr-namespace:MyNamespace" 
    Title="MainWindow" Height="350" Width="525"> 


    <local:MyCustomLayout x:Name="myLayout"/> 
</Window> 

一切都顯示accordingly.Now我的目標是加強一個由ThirdPartyLayout面板中顯示的子組件之一的顯示,被叫TargetControl。所以,我添加以下代碼:

<Window.Resources> 
    <Style TargetType="{x:Type sdk:TargetControl}"> 
     <Style.Resources> 
      <ToolTip x:Key="ToolTipContent"> 
       <StackPanel> 
        <TextBlock FontWeight="Bold" Text="Testing 1 2 3"/> 
        <TextBlock Text="{Binding Name}"/> 
       </StackPanel> 
      </ToolTip> 
     </Style.Resources> 
     <Setter Property="ToolTip" Value="{StaticResource ToolTipContent}"/> 
    </Style> 
</Window.Resources> 

當我運行的代碼中,「測試1 2 3」的消息顯示正確,但是,我沒有看到Name屬性。在輸出窗口,我得到以下信息:

BindingExpression path error: 'Name' property not found on 'object' ''MyViewController' (HashCode=31884011)'

我不明白的是,爲什麼結合,而不是TargetControl類是發生在MyViewController類。有任何想法嗎?

最好的問候, 卡洛斯·喬丹

編輯:

主要是修修補補指南由福利局給出的建議後,我最終發現該錯誤的來源其實是在SDK中。目前的版本仍然有問題,但是當從源代碼編譯時,我會得到預期的行爲。

感謝您的幫助。

回答

1

在XAML中創建綁定時,默認情況下,綁定到當前的DataContext。在這個例子中,MyViewController似乎是sdk:TargetControl的DataContext。綁定到skd:TargetControlName屬性代替,請嘗試以下操作:

<TextBlock Text="{Binding Name, RelativeSource={RelativeSource AncestorType={x:Type sdk:TargetControl}}}"/> 
+0

這似乎是在正確的方向。使用RelativeSource = {RelativeSource Self}}仍會拋出一個錯誤,因爲它試圖綁定到TextControl。使用RelativeSource = {RelativeSource TemplatedParent}會使錯誤在輸出中消失,但綁定仍然不起作用。有什麼想法嗎? – user1139216

+0

@ user1139216我很匆忙地把目標弄亂了。如果您願意,請嘗試編輯。 – newb

+0

隨着編輯,我在輸出中得到錯誤:「無法找到與參考綁定的源'RelativeSource FindAncestor,AncestorType ='skd:TargetControl',AncestorLevel ='1''。BindingExpression:Path = Name「 – user1139216

1

好像MyViewController的xaml.cs的DataContext的有MyCustomItem的參考。

如果你希望你可以在xaml.cs中設置MyCustomLayout.ItemsSource = this.DataContext。

或者你可以做MyCustomLayout.ItemsSource = MyCustomItem的特定屬性。

+0

我給了這個+ 1,因爲它確實與SDK中糾正的問題有一些關係,但我正在爲newb設置答案,因爲這正是我指出的正確方向。 – user1139216