【问题标题】:WPF How must I set the DataContextWPF 我必须如何设置 DataContext
【发布时间】:2013-02-13 04:55:24
【问题描述】:

我有一个从列表框继承的控件。 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 的绑定不起作用。

【问题讨论】:

    标签: wpf xaml binding datacontext


    【解决方案1】:

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

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

    不要忘记实现预更改通知,否则它不会对更改做出反应。 或者,您可以将ItemHeight 添加到DockItem 类,那么您当前的方法就可以了。

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 2015-03-19
      • 1970-01-01
      • 2014-04-04
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      相关资源
      最近更新 更多