【问题标题】:Exposing a sub-control in a UserControl for use in XAML在 UserControl 中公开子控件以在 XAML 中使用
【发布时间】:2009-01-29 17:39:51
【问题描述】:

我有一个包含 TreeView 的 UserControl。我希望用户能够通过 XAML 设置内部 TreeView 控件的属性,但我不知道该怎么做。

我尝试在 UserControl 上为 TreeView 创建一个公共属性,但这仅允许我设置 SelectedItemChanged 触发器。

我想做这样的事情:

<ExampleUserControl>
    <ExampleUserControl.TreeView.ItemTemplate>
        ...
    </ExampleUserControl.TreeView.ItemTemplate>
</ExampleUserControl>

或者:

<ExampleUserControl TreeView.ItemsSource="{Binding Foo}" />

我不希望在 UserControl 中为每个 TreeView 属性创建属性,并且我不想强制用户在 C# 中定义控件。

【问题讨论】:

  • 您不能在 xaml 标记 () 中堆叠属性。而且您可能无法将树视图公开为公共财产;无论如何,这将是糟糕的juju。很可能您需要在用户控件上创建 dp 并使用模板绑定。

标签: wpf xaml


【解决方案1】:

至于在用户控件中将多个属性传递给子控件,您始终可以公开一个 Style 属性。

即儿童风格

对于 ItemsSource,除非您使用 [Josh Smith 的 Element Spy / Data Context Spy / Freezable][1] 技巧,否则您将在 DataContexts 上断开连接。

所以要么使用这些技巧,要么只拥有 2 个属性。

1) ItemsSource 2)儿童风格

xaml 结束了...

    <ChildTreeAnswer:MyControl ItemsSource="{Binding Items}">
        <ChildTreeAnswer:MyControl.ChildStyle>
            <Style>
                <Setter Property="ItemsControl.ItemTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <Border BorderBrush="Black"
                                    BorderThickness="1"
                                    Margin="5">
                                <TextBlock Text="{Binding }" />
                            </Border>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ChildTreeAnswer:MyControl.ChildStyle>                           
    </ChildTreeAnswer:MyControl>

然后在您的用户控件中...(为了简单起见,我使用了一个列表框)

    <ListBox ItemsSource="{Binding ItemsSource}"
             Style="{Binding ChildStyle}" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2015-04-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多