WPF Custom Control for Side by Side Layout

自闭症网瘾萝莉.ら 提交于 2019-12-06 06:51:04

The direct answer is that you need an ItemsPresenter in your ControlTemplate, which would look something like this:

<ItemsControl x:Class="ItemsControlExample"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ItemsControl.Template>
        <ControlTemplate TargetType="ItemsControl">
            <Border SnapsToDevicePixels="True">
                <!-- Collection items are displayed by the ItemsPresenter. --> 
                <ItemsPresenter SnapsToDevicePixels="True" />
            </Border>
        </ControlTemplate>
    </ItemsControl.Template>

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <!-- Replace the default vertical StackPanel with horizontal. -->
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemContainerStyle>
        <Style TargetType="...">
            <!-- The same container style applies to all items so where do you put the splitter? -->
        </Style>
    </ItemsControl.ItemContainerStyle>    

</ItemsControl>

But it should be obvious now that ItemsControl doesn't align to your use case. However, you can implement it as a Control using the ControlTemplate you already have with a ContentControl the PART_LeftContent and PART_RightContent grid cells:

<!-- LeftSideContent is a DependencyProperty of type object -->
<ContentControl x:Name="LeftContentControl" Content="{TemplateBinding LeftSideContent}" />

Then extend your code to handle the ContentControl mouse events in order to select and add style triggers for the selected appearance, but that's pretty straightforward stuff. If you haven't implemented lookless controls before you should be aware that you can't define event callbacks in the template, but instead have to hook them in your code:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    ContentControl lc = (ContentControl)base.GetTemplateChild("LeftContentControl"));
    // check for null in case the active template doesn't have a 'LeftContentControl' element
    if (lc != null) 
    {
        // Use these events to set SelectedItem DependencyProperty and trigger selected item 
        // highlight style. Don't forget to capture the mouse for proper click behavior.
        lc.MouseDown += new MouseButtonEventHandler(LeftSide_MouseDown);
        lc.MouseUp += new MouseButtonEventHandler(LeftSide_MouseUp);
    }
 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!