2013-02-27 78 views
0

我有一個從ListBox繼承的控件。 的XAML看起來是這樣的:WPF如何設置DataContext

<ListBox x:Class="Bibliothek.myDockControl" 
     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" 
     mc:Ignorable="d" 
     d:DesignHeight="300" d:DesignWidth="300" 
     x:Name="myListBox" 
     > 
<ListBox.ItemContainerStyle> 
    <Style TargetType="ListBoxItem"> 
     <Setter Property="Height" Value="{Binding ItemHeight, UpdateSourceTrigger=PropertyChanged}"/> 
     <Setter Property="Template">   
      <Setter.Value> 
       <ControlTemplate TargetType="ListBoxItem"> 
        <Border BorderThickness="1" BorderBrush="Black" CornerRadius="2"> 
         <DockPanel> 
          <StackPanel DockPanel.Dock="Top" Background="LightGray"> 
           <DockPanel Margin="2,2,2,2"> 
            <TextBlock x:Name="Beschreibung" DockPanel.Dock="Left" VerticalAlignment="Center" FontWeight="Bold" Text="{Binding Header,UpdateSourceTrigger=PropertyChanged}"></TextBlock> 
           </DockPanel> 
          </StackPanel> 
          <ContentPresenter DockPanel.Dock="Top" Content="{Binding Content}"></ContentPresenter> 
         </DockPanel> 
        </Border>           
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</ListBox.ItemContainerStyle> 

我有一個在文本塊,爲contentpresenter結合。這些綁定來自我自己的類型DockItem。看起來像這樣:

public class DockItem 
{ 
    public string Header { get; set; } 
    public object Content { get; set; } 
} 

這些屬性用於結合被設置在其中,i測試的控制,是從被綁定到列表框的典型的ItemSource的ObservableCollection窗口。

當我添加一個綁定的Height屬性像上面(ItemHeight)在後面的代碼中聲明我不知道如何設置datacontext。如果我在列表框控件的代碼隱藏中設置datacontext,如下所示:DataContext = this;那麼標題和內容的綁定不起作用。

回答

2

您正試圖將兩個不同的數據上下文設置爲一個ListBoxItem。 如果你一定要採取ItemHeight從父窗口,那麼你可以把它像這樣:

<Setter Property="Height" Value="{Binding ItemHeight, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"/> 

唐`噸忘記實現preperty雖然改變的通知,或者向那倒變化作出反應。 或者,您可以將ItemHeight添加到DockItem類,那麼您目前的方法可以正常工作。

相關問題