0

我有一个从列表框继承的控件。XAML 如下所示:

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

我有一个 Textblock 和 contentpresenter 的绑定。这些绑定来自我自己的类型 DockItem。看起来像这样:

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

绑定的这些属性是在我测试控件的窗口中设置的,并且来自绑定到列表框的 itemsource 的 typ observablecollection。

当我为上面代码中声明的 Height 属性(如 ItemHeight)添加绑定时,我不知道如何设置数据上下文。如果我在列表框控件的代码隐藏中设置 datacontext,如下所示: DataContext = this; 那么 Header 和 Content 的绑定不起作用。

4

1 回答 1

2

您正在尝试将两个不同的数据上下文设置为一个ListBoxItem。如果您确实想从父窗口中获取 ItemHeight,那么您可以这样:

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

不过不要忘记实现预更改通知,否则它不会对更改做出反应。或者,您可以添加ItemHeightDockItem课程中,那么您当前的方法就可以了。

于 2013-02-27T13:34:41.240 回答