0

I have a Control inherited from a Listbox. The XAML looks like this:

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

I have a binding for the Textblock and for the contentpresenter. these bindings are from my own type DockItem. Looks like this:

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

these property for the binding is set in the window where i tested the control and is from typ observablecollection which is binded to the itemsource of the listbox.

when i added a binding for the Height property like above(ItemHeight) that is declared in the code behind i don't know how to set the datacontext. If I set the datacontext in the codebehind of the listbox control like this: DataContext = this; then the bindings for the Header and Content doesnt work.

1 Answer 1

2

You`re trying to set two different data contexts to one ListBoxItem. If you definitely want to take ItemHeight from parent Window, then you can make it like this:

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

Don`t forget to implement preperty changed notification though, or it won`t react to changes. Alternatively you can add ItemHeight to DockItem class, then your current approach will work ok.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.